<?php
namespace app\oem\controller;
use think\Controller;
use think\Db;
use app\common\controller\OemBaseController;
use app\common\model\Csv;

class Accounts extends OemBaseController
{
 	protected $csv;
    protected function _initialize() {
        parent::_initialize();
        $this->csv = new Csv();
    }
    //批量处理店铺显示隐藏	
	public function chuli(){
		$where['id']=["in",input()['arr']];
		$up['is_huilu'] = input('status');
		$res=db("info_agent")->where($where)->update($up);
		if($res){
			return json(['code'=>200,'msg'=>'操作成功']);
		}else{
			return json(['code'=>400,'msg'=>'操作失败']);
		}
	}	
    //商家推荐人
    function show_city_pt(){
    	$agent_id = input('agent_id');
    	//获取商家信息
    	$agent_info = db('info_agent')->where('id',$agent_id)->find();
    	if($agent_info['city_pt'] > 0){
    		$user_info = db('info_user')->where('id',$agent_info['city_pt'])->find();
    		$agent_info['city_pt_mobile'] = $user_info['mobile'];
    	}else{
    		$agent_info['city_pt_mobile'] = '';
    	}
    	
    	if($_POST){
    		$user_info = db('info_user')->where('id',input('city_mobile'))->find();
    		if($user_info){
    			//更新商家信息
				$result = db('info_agent')->where('id', input('agent_id'))->update(['city_pt' => $user_info['id']]);
	    		
				if($result){
					return json(["code"=>200,'msg'=>'添加成功']);
				}else{
					return json(["code"=>400,'msg'=>'添加失败']);
				}
    		}else{
    			return json(["code"=>200,'msg'=>'用户不存']);
    		}
    	}
    	$this->assign('agent_info',$agent_info);
    	return $this->fetch();
    }
    
    
    //市代推荐人
    function show_province_pt(){
    	$city_id = input('city_id');
    	//获取市代信息
    	$city_info = db('info_oem')->where('id',$city_id)->find();
    	if($city_info['oem_pt'] > 0){
    		$user_info = db('info_user')->where('id',$city_info['oem_pt'])->find();
    		$city_info['province_pt_mobile'] = $user_info['mobile'];
    	}else{
    		$city_info['province_pt_mobile'] = '';
    	}
    	
    	if($_POST){
    		$user_info = db('info_user')->where('id',input('city_mobile'))->find();
    		if($user_info){
    			//更新市代信息
				$result = db('info_oem')->where('id', $city_id)->update(['oem_pt' => $user_info['id']]);
	    		
				if($result){
					return json(["code"=>200,'msg'=>'添加成功']);
				}else{
					return json(["code"=>400,'msg'=>'添加失败']);
				}
    		}else{
    			return json(["code"=>200,'msg'=>'用户不存']);
    		}
    	}
    	$this->assign('city_info',$city_info);
    	return $this->fetch();
    }
    
    //省代推荐人
    function show_oem_pt(){
    	$province_id = input('province_id');
    	//获取市代信息
    	$province_info = db('info_oem')->where('id',$province_id)->find();
    	if($province_info['oem_pt'] > 0){
    		$user_info = db('info_user')->where('id',$province_info['oem_pt'])->find();
    		$province_info['province_pt_mobile'] = $user_info['mobile'];
    	}else{
    		$province_info['province_pt_mobile'] = '';
    	}
    	
    	if($_POST){
    		$user_info = db('info_user')->where('id',input('city_mobile'))->find();
    		if($user_info){
    			//更新市代信息
				$result = db('info_oem')->where('id', $province_id)->update(['oem_pt' => $user_info['id']]);
	    		
				if($result){
					return json(["code"=>200,'msg'=>'添加成功']);
				}else{
					return json(["code"=>400,'msg'=>'添加失败']);
				}
    		}else{
    			return json(["code"=>200,'msg'=>'用户不存']);
    		}
    	}
    	$this->assign('province_info',$province_info);
    	return $this->fetch();
    }
    
    //解除合伙人	
	public function jiechu(){
		$res=db('info_user')->where("id",input("id"))->update(["is_pt1"=>0]);
		if($res){
			return json(['code'=>200,'msg'=>'操作成功']);
		}else{
			return json(['code'=>404,'msg'=>'操作失败']);
		}
	}	
	//添加合伙人
	public function pt_add(){
		$area=db('info_oem')->where('id',session("d_id"))->find();
		if($_POST){
			$user_level=session("user_level");
			$where['mobile']=input("mobile");
			$user=db('info_user')->where($where)->find();
			
			if(!$user){
				return json(['code'=>404,'msg'=>'该手机号码会员不存在!无法添加']);
			}else{
				if($user['is_pt1']==1){
					return json(['code'=>404,'msg'=>'改号码已经是市场专员了,请勿重复添加']);
				}
				$update['tj_pt1']=$user['id'];
				$update['is_pt1']=1;
				$update['agency_id']  = $area['province_id'];
				$update['agency_id1'] = $area['agency_id'];
				$update['agency_id2'] = $area['id'];
				$update['pt_time']=now_time();
				$update['sc_bili']=input("sc_bili");
				$res=db('info_user')->where($where)->update($update);
				if($res){
					return json(['code'=>200,'msg'=>'操作成功']);
				}else{
					return json(['code'=>404,'msg'=>'操作失败']);
				}
			}
		}
		$this->assign('area',$area);
		return $this->fetch();
	}	
	
	//合伙人列表
	public function pt_user(){ 
		$user_level=session("user_level");
		// if($user_level==1){//oem
		// 	$where['a.oem_id']=session('d_id');
		// }
		if($user_level==2){//市代理
			$where['a.agency_id1']=session('d_id');
		}
		if($user_level==3){//区域运营商
			$where['a.agency_id2']=session('d_id');
		}
		if($user_level==4){//省级代理
			$where['a.agency_id']=session('d_id');
		}
		
		if(input('mobile')){
			$where['a.mobile'] =['like','%'.input('mobile').'%'];
		}

		if(input('agency_id')){
			$where['a.agency_id'] = input('agency_id');
		}
        if(input('agency_id1')){
			$where['a.agency_id1'] = input('agency_id1');
		}
        if(input('agency_id2')){
			$where['a.agency_id2'] = input('agency_id2');
		}
		$where['a.is_pt1'] = 1;
		
		$field="a.*,b.*,c.user_name as oemname,d.user_name as agency_name,e.user_name as city_name"; 
		$list_tj=db('info_agent')->field("sc_id,count(sc_id) b")->group("sc_id")->buildSql(); 
		$list=db('info_user ')->alias('a')
				->join($list_tj." b","b.sc_id=a.id",'left')
				->join("info_oem c","c.id=a.agency_id",'left')
				->join("info_oem d","d.id=a.agency_id1",'left')
				->join("info_oem e","e.id=a.agency_id2",'left')
				->field($field)
				->where($where)
				->order('pt_time desc')
				->paginate(10,false,['query'=>request()->param()]);		
				//->buildSql();dump($list);exit;
				
		$this->assign('sel_mobile',input('mobile'));
		$this->assign('sel_oem',input('ch_agency'));
		$this->assign('list',$list);
		
		
		$province_where['user_level']=4;
		$agency_where['user_level']=2;
		$area_where['user_level']=3;
		//获取运营中心列表
		if($user_level==1){//平台
			$agency_where['oem_id']=session('d_id');
		}

		if($user_level==4){//省级代理
			$agency_where['province_id']=session('d_id');
		}

		if($user_level==2){//省级代理
			$area_where['agency_id']=session('d_id');
		}

		$province = db('info_oem')->field('id,user_name')->where($province_where)->select();
		$agency = db('info_oem')->field('id,user_name')->where($agency_where)->select();
		$area = db('info_oem')->field('id,user_name')->where($area_where)->select();

		$this->assign('province',$province);
		$this->assign('agency',$agency);
		$this->assign('area',$area);
		$this->assign('agency_id',input('agency_id'));
		$this->assign('mobile',input('mobile'));
		$this->assign('agency_id1',input('agency_id1'));
		$this->assign('agency_id2',input('agency_id2'));
		return $this->fetch();
	}
	
	
	
    
	//帐号管理
	public function user()
    {
    	$user_level=session("user_level");
		$where = [];
		$sel_agent = [];
		if($user_level==2){//省代理
			$where['a.agency_id1']=session('d_id');
			$data['agency_id1']=session('d_id');
			$sel_agent['agency_id1'] = session('d_id');
		}
		if($user_level==3){
			$where['a.agency_id2']=session('d_id');
			$data['agency_id2']=session('d_id');
			$sel_agent['agency_id2'] = session('d_id');
		}
		if($user_level==4){
			$where['a.agency_id']=session('d_id');
			$data['agency_id']=session('d_id');
			$sel_agent['agency_id'] = session('d_id');
		}

		$mobile="";
		$user_no="";
		$agent_id="";
		$agency_id="";
		$agency_id1="";
		$agency_id2="";

		if(input("mobile")){
			$mobile=input("mobile");
			$data['mobile']=["like","%".$mobile."%"];
			$where['a.mobile']=["like","%".$mobile."%"];
		}
		
		if(input("user_no")){
			$user_no=input("user_no");
			$data['id'] =$user_no;
			$where['a.id']=$user_no;
		}

		if(input('agent_id')){
			$agent_id = input('agency_id1');
			$data['tj_agent'] = $agent_id;
			$where['a.tj_agent'] = $agent_id;
		}

        if(input('agency_id')){
			$agency_id = input('agency_id');
			$data['agency_id'] = $agency_id;
			$query['a.agency_id'] = $agency_id;
			$where['a.agency_id'] = $agency_id;
		}

		if(input('agency_id1')){
			$agency_id1 = input('agency_id1');
			$data['agency_id1'] = $agency_id1;
			$query['a.agency_id1'] = $agency_id1;
			$where['a.agency_id1'] = $agency_id1;
		}
		
		if(input('agency_id2')){
			$agency_id2=input('agency_id2');
			$data['agency_id2'] = $agency_id2;
			$query['a.agency_id2'] = $agency_id2;
			$where['a.agency_id2'] = $agency_id2;
		}
		
		$this->assign("mobile",$mobile);
		$this->assign("user_no",$user_no);
		$this->assign("agent_id",$agent_id);
		$this->assign("agency_id",$agency_id);
		$this->assign("agency_id1",$agency_id1);
		$this->assign("agency_id2",$agency_id2);
		
		$data['is_fx'] = 1;
		$fx_total=db("info_user")->where($data)->count();
		$this->assign("fxs",$fx_total);
		$level = db('info_user')->field('count(id) as count,level')->group('level')->buildSql();
		$cz = db('log_paylog_copy')->field('sum(balance) as cz,uid')->where("order_type=8")->group('uid')->buildSql();
		
    	$list=db('info_user')->alias('a')		
		->join($level.'b','b.level = a.id','LEFT')
		->join('info_oem c','a.agency_id2 = c.id','LEFT')
		->join("info_agent d","a.tj_agent=d.id",'LEFT')
		->join("info_user e","a.level=e.id",'LEFT')
		->join($cz."f","f.uid=a.id",'LEFT')
		->field('a.is_fx,f.cz,a.id,a.user_name,a.mobile,a.balance,a.commission,a.score,a.status,a.add_time,a.nickname,a.reg_type,a.openid,a.alipay_id,b.count,c.user_name as city_name,d.agent_name,e.mobile as tmobile,e.nickname as tnickname')
		->where($where)->order('a.add_time desc')
		//->buildSql();
		//dump($list);
		->paginate(15,false,['query'=>request()->param()]);
		$this->assign("list",$list);
		$this->assign('empty','<span class="empty" style="margin-top:5%">没有数据</span>');
		
		// if(session('d_id')==1){
		// 	$wheres['oem_id'] = session('d_id');
		// }else{
		// 	$wheres['agency_id'] = session('d_id');
		// }
		
		// //$wheres['user_level'] = 3;
		// //获取服务商列表
		// $city = db('info_oem')->field('id,user_name')->where($wheres)->where('user_level',3)->select();
		// $this->assign('city',$city);
		// //获取运营商列表
		// $yys = db('info_oem')->field('id,user_name')->where($wheres)->where('user_level',2)->select();
		// $this->assign('yys',$yys);
		$province_where['user_level']=4;
		$agency_where['user_level']=2;
		$area_where['user_level']=3;
		//获取运营中心列表
		if($user_level==1){//平台
			$agency_where['oem_id']=session('d_id');
		}

		if($user_level==4){//省级代理
			$agency_where['province_id']=session('d_id');
		}

		if($user_level==2){//省级代理
			$area_where['agency_id']=session('d_id');
		}

		$province = db('info_oem')->field('id,user_name')->where($province_where)->select();
		$agency = db('info_oem')->field('id,user_name')->where($agency_where)->select();
		$area = db('info_oem')->field('id,user_name')->where($area_where)->select();

		$this->assign('province',$province);
		$this->assign('agency',$agency);
		$this->assign('area',$area);
		//商家列表
		$agent_list = db('info_agent')->field('id,agent_name')->where($sel_agent)->select();
		$this->assign('agent_list',$agent_list);
		
		
    	return $this->fetch();
    }
	   //门店收款二维码
	public function fukuan()
    {
    	$agent_info = db('info_agent')->where('id',input("id"))->find();
    
    	$code_url="http://".$_SERVER['HTTP_HOST']."/index/pay/qrcode_pay?agent_id=".$agent_info['id']."&clerk_id=0";
    	
    	$agent_info['code_url'] = $code_url;
    
    	$this->assign('agent_info',$agent_info);
    
    	
    	return $this->fetch();
    }
    //会员改变状态
	public function user_status()
    {
    	$where['status'] = input('status');
    	$ress = db('info_user')->where('id',input('id'))->update($where);
    	if($ress){
			return json(['code'=>200,'msg'=>'成功']);
		}else{
			return json(['code'=>402,'msg'=>'失败']);
		}
    }
	 //会员改变状态
	public function user_sx()
    {
    	$where['openid'] ="";
		$where['mobile'] ="";
		$where['alipay_id'] ="";
    	$ress = db('info_user')->where('id',input('id'))->update($where);
    	if($ress){
			return json(['code'=>200,'msg'=>'操作成功']);
		}else{
			return json(['code'=>402,'msg'=>'操作失败']);
		}
    }
    public function agent()
    {
    	$user_level=session("user_level");
		if($user_level==1){//oem
			$where['a.oem_id']=session('d_id');
		}
		if($user_level==2){//省代理
			$where['a.agency_id1']=session('d_id');
		}
		if($user_level==3){
			$where['a.agency_id2']=session('d_id');
		}
		if($user_level==4){
			$where['a.agency_id']=session('d_id');
		}
		
			$agent_name="";
			$mobile="";
			$cm="";
			$ch_city="";
			$agency_id1=0;
			$agency_id="";

		if(input('agent_name')){
			$query['a.agent_name'] = input('agent_name');
			$agent_name = input("agent_name");
			$where['a.agent_name'] = ['like', '%'.input('agent_name').'%'];
		}
		
		if(input('mobile')){
			$query['a.mobile'] = input('mobile');
			$mobile=input("mobile");
			$where['a.mobile'] = input('mobile');
		}   

		if(input('cm')){ 
			$cm=input("cm");
			$where['u.mobile'] = input('cm');
		}

		if(input('ch_city')){
			$ch_city=input('ch_city');
			$query['a.agency_id2'] = input('mobile');
			$where['a.agency_id2'] = input('ch_city');
		}

		if(input('operator')){
			$agency_id1=input('operator');
			$where['a.agency_id1'] = input('operator');
		}

		if(input('province')){
			$agency_id=input('province');
			$where['a.agency_id'] = input('province');
		}

			$this->assign("agent_name",$agent_name);
			$this->assign("mobile",$mobile);
			$this->assign("cm",$cm);
			$this->assign("ch_city",$ch_city);
			$this->assign("agency_id1",$agency_id1);
			$this->assign("agency_id",$agency_id);
		
		
		//排序
		$order = 'a.add_time desc';
		//$order = 'b.count|a.score desc';
		if(input('order')){
			if(input('order') == 1){
				//鼓励金排序
				$this->assign("order",1);
				$order = 'a.score desc';
			}else{
				//推广数
				$this->assign("order",2);
				$order = 'b.count desc';
			}
		}else{
			$this->assign("order",0);
		}
		
		//推广
		$tjagent = db('info_user')->field('count(id) as count,tj_agent')->group('tj_agent')->buildSql();
		//合伙人
		$puuser = db('info_user')->field('count(id) as counts,tj_agent')->where('is_pt',1)->group('tj_agent')->buildSql();
		//分享会员个数 
		$share_user  = db('info_user')->field('count(id) as share_count,tj_agent')->where('is_fx',1)->group('tj_agent')->buildSql();
		//绑定二维码数量 
		$agent_qr_code  = db('agent_qr_code')->field('count(id) as code_count,agent_id')->group('agent_id')->buildSql();
        //是否分类
		$agent_relate_category  = db('agent_relate_category')->field('count(id) as category_count,agent_id')->group('agent_id')->buildSql();

		
    	$list=db('info_agent')->alias('a')		
		->join($tjagent.'b','b.tj_agent = a.id','LEFT')
		->join($puuser.'c','c.tj_agent = a.id','LEFT')
		->join('info_oem d','a.agency_id2 = d.id','LEFT')
		->join('info_oem e','e.id=d.agency_id','LEFT')
		->join('info_user u','u.id=a.sc_id','LEFT')
		->join($share_user.'f','f.tj_agent = a.id','LEFT')
		->join($agent_qr_code.'h','h.agent_id = a.id','LEFT')
		->join($agent_relate_category.'t','t.agent_id = a.id','LEFT')
		->where($where)
		->field('u.mobile as cm,a.id,a.ad_score,a.agent_name,a.is_huilu,a.mobile,a.balance,a.score,a.store_property,a.address,a.is_state,a.status,a.add_time,b.count,c.counts,d.user_name as city_name,e.user_name as operator_name,f.share_count,h.code_count,t.category_count')
		->order($order)
		->paginate(15,false,['query'=>request()->param()]);
		
		$this->assign("list",$list);
		$this->assign('empty','<span class="empty" style="margin-top:5%">没有数据</span>');
		
		$province_where['user_level']=4;
		$agency_where['user_level']=2;
		$area_where['user_level']=3;
		//获取运营中心列表
		if($user_level==1){//平台
			$agency_where['oem_id']=session('d_id');
		}

		if($user_level==4){//省级代理
			$agency_where['province_id']=session('d_id');
		}

		if($user_level==2){//省级代理
			$area_where['agency_id']=session('d_id');
		}

		$province = db('info_oem')->field('id,user_name')->where($province_where)->select();
		$agency = db('info_oem')->field('id,user_name')->where($agency_where)->select();
		$area = db('info_oem')->field('id,user_name')->where($area_where)->select();
		
		$this->assign('province',$province);
		$this->assign('agency',$agency);
		$this->assign('area',$area);
    	return $this->fetch();
    }
	//商家改变状态
	public function agent_status()
    {
    	$where['status'] = input('status');
    	$ress = db('info_agent')->where('id',input('id'))->update($where);
    	if($ress){
			return json(['code'=>200,'msg'=>'成功']);
		}else{
			return json(['code'=>402,'msg'=>'失败']);
		}
    }
    //修改商家显示状态
    function agent_display(){
    	$where['is_huilu'] = input('status');
    	$ress = db('info_agent')->where('id',input('id'))->update($where);
    	if($ress){
			return json(['code'=>200,'msg'=>'成功']);
		}else{
			return json(['code'=>402,'msg'=>'失败']);
		}
    }
	
	public function show_agent(){
		$account=db('info_agent')->find(input("id"));
		$this->assign('ad',$account);
		return $this->fetch();
	}
	//修改商家费率
	public function upagent_huilv()
    {
    	if(request()->isPost()){
	    	$where['temp_fee'] = input('cb_huilu');
			$where['is_huilu'] = 2;
	    	$ress = db('info_agent')->where('id',input('id'))->update($where);
	    	if($ress){
				return json(['code'=>200,'msg'=>'提交成功等待通过']);
			}else{
				return json(['code'=>402,'msg'=>'提交失败']);
			}
    	}
    	$this->assign("id",input('id'));
    	return $this->fetch();
	}
	

	//清空推荐人
	public function clear_pt(){
		$res=db("info_oem")->where("id",input("id"))->update(['oem_pt'=>0]);
		if($res){
			return json(['code'=>200,'msg'=>'操作成功']);
		}
		return json(['code'=>400,'msg'=>'操作失败']);
	}


	//显示页面
    public function qr_code()
    {
		
		$info_ome = db('info_oem')->where('id',session('d_id'))->find();
		$where1['oem_id']=1;
		$where1['user_level']=2;
		$info_ome_number = db('info_oem')->where($where1)->select();



		if($info_ome['user_level']==2){
			$where['cb_no']=$info_ome['cb_no'];
		}
		if($info_ome['user_level']==3){
            $where['regional_id']=$info_ome['id'];
		}

		//二维码条件查询
    	if(request()->isPost()){
    		
    		$param=input('post.');
			
			if(!empty($param['qr_code_number']))$where['qr_code_number'] = ['like','%'.$param['qr_code_number'].'%'];
			
			
			if(!empty($param['agent_id']))$where['agent_id'] = $param['agent_id'];
	   
			if($info_ome['user_level']==2){
			if(!empty($param['regional_id']))$where['regional_id'] = $param['regional_id'];
			}

			if($info_ome['user_level']==1 || $info_ome['user_level']==2){
				if(!empty($param['oem_id']))$where['oem_id'] = $param['oem_id'];
			}

		}  
		
		$qr_code_status = 0;
		if(input('qr_code_status')){
			$qr_code_status=input('qr_code_status');
			$where['qr_code_status'] =  $qr_code_status;
		}

        //默认全部显示
		$status = 1;
		$where['status']  = $status;
        $this->assign('status',$status);
		$this->assign('qr_code_status',$qr_code_status);

   
		//获取全部二维码
		$agent_qr_code_list = db('agent_qr_code')
						->where($where)
						->order('id desc')
						->paginate(10,false,['query'=>request()->param()]);

        //sum显示页总数，$sum2未绑定总数，$sum3绑定总数
		$sum=db('agent_qr_code')->where($where)->count();

		if(!empty($where['qr_code_status'])){
			if($where['qr_code_status']==1){
				$sum2=db("agent_qr_code")->where($where)->count();
				$sum3=$sum-$sum2;
			}
			if($where['qr_code_status']==2){
				$sum3=db("agent_qr_code")->where($where)->count();
			    $sum2=$sum-$sum3;
			}
	    }else{
			$where['qr_code_status']=2;
			$sum3=db("agent_qr_code")->where($where)->count();
			$sum2=$sum-$sum3;
		}

		//隐藏总数
        $where['status']=2;
		$sum4=db("agent_qr_code")->where($where)->count();
    
		$this->assign('qr_code_number',trim(input('qr_code_number')));
		$this->assign('agent_id',input('agent_id'));
		$this->assign('regional_id',input('regional_id'));
		$this->assign('oem_id',input('oem_id'));
		$this->assign('agent_qr_code_list',$agent_qr_code_list);
		$this->assign('info_ome_number',$info_ome_number);
		$this->assign('info_ome',$info_ome);
		$this->assign('sum',$sum);
		$this->assign('sum2',$sum2);
		$this->assign('sum3',$sum3);
		$this->assign('sum4',$sum4);
		$this->assign('empty','<span class="empty" >没有数据</span>');
    	return $this->fetch();
	}

	//完善商家分类信息
	public function wanshan(){
		$agent_id=input('id');
		$where1['category_type']=1;
		$agent_category_info = db('agent_category')->where($where1)->order('category_sort','asc')->select();
		if(request()->isPost()){
			$agent_id=input('agent_id');
			$category_id=implode(',' ,$_POST['category']);

			$param['category_id']=$category_id;
			$param['agent_id']=$agent_id;

            $tag['tag_agent_id']=$agent_id;
			$tag['tag_1']=input('tag_1');
			$tag['tag_2']=input('tag_2');
			$tag['tag_3']=input('tag_3');
			$tag['tag_4']=input('tag_4');
			$tag['tag_5']=input('tag_5');

			//商家分类添加修改
			$agent_relate_category = db('agent_relate_category')->where('agent_id',$agent_id)->find();
			if($agent_relate_category){
				$res = db('agent_relate_category')->where('agent_id',$agent_id)->update($param);
			}else{
				$res = db('agent_relate_category')->insert($param);
			}

			//商家标签修改
			$agent_tag = db('agent_tag')->where('tag_agent_id',$agent_id)->find();
			if($agent_tag){
				$res2 = db('agent_tag')->where('tag_agent_id',$agent_id)->update($tag);
			}else{
				$res2 = db('agent_tag')->insert($tag);
			}

            if($res || $res2){
				return json(['msg'=>'设置成功','code'=>200]);
			}else{
				return json(['msg'=>'设置失败','code'=>402]);
			}
		}
		$agent_category_id=array();
		$agent_category = db('agent_relate_category')->where('agent_id',$agent_id)->find();
		if($agent_category){
			$agent_category_id= explode(",",$agent_category['category_id']);
		}
	
		$agent_tag = db('agent_tag')->where('tag_agent_id',$agent_id)->find();
	    $this->assign('agent_tag',$agent_tag);
		$this->assign('agent_category_id',$agent_category_id);
		$this->assign('agent_category_info',$agent_category_info);
		$this->assign('agent_id',$agent_id);
		return $this->fetch();
	}

	//隐藏页面
    public function qr_code2()
    {
		$info_ome = db('info_oem')->where('id',session('d_id'))->find();

		$where1['oem_id']=1;
		$where1['user_level']=2;
		$info_ome_number = db('info_oem')->where($where1)->select();

		if($info_ome['user_level']==2){
			$where['cb_no']=$info_ome['cb_no'];
		}
		if($info_ome['user_level']==3){
            $where['regional_id']=$info_ome['id'];
		}

		//二维码条件查询
    	if(request()->isPost()){
    		
    		$param=input('post.');
			
			if(!empty($param['qr_code_number']))$where['qr_code_number'] = ['like','%'.$param['qr_code_number'].'%'];
			
			if(!empty($param['agent_id']))$where['agent_id'] = $param['agent_id'];

			if($info_ome['user_level']==2){
			if(!empty($param['regional_id']))$where['regional_id'] = $param['regional_id'];
			}
			
		}  
		
		//一定绑定
		$qr_code_status = 2;
		if(input('qr_code_status')){
			$qr_code_status=input('qr_code_status');
			$where['qr_code_status'] =  $qr_code_status;
		}
        //隐藏页
		$status = $where['status']  = 2;
		
        $this->assign('status',$status);
		$this->assign('qr_code_status',$qr_code_status);

		

   
		//获取全部二维码
		$agent_qr_code_list = db('agent_qr_code')
						->where($where)
						->order('id desc')
						->paginate(20,false,['query'=>request()->param()]);
			
		$this->assign('qr_code_number',trim(input('qr_code_number')));
		$this->assign('agent_id',input('agent_id'));
		$this->assign('regional_id',input('regional_id'));
		$this->assign('oem_id',input('oem_id'));
		$this->assign('agent_qr_code_list',$agent_qr_code_list);
		$this->assign('info_ome_number',$info_ome_number);
		$this->assign('info_ome',$info_ome);

		$this->assign('empty','<span class="empty" >没有数据</span>');
    	return $this->fetch();
	}

	//代理批量生成二维码
	public function add_qr_code_number()
    {
		if(request()->isPost()){
		$code_number=input('code_number');
		for ($x=1; $x<=$code_number; $x++) {
			//代理编号+3位随机数+时间戳+3位随机数+循环序号
			$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
			$outputstr = "";
			for ($i=0; $i<4; $i++)
			{
				$outputstr .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
			}
			$code['qr_code_number'] = $outputstr.rand(0,999).time().$x.rand(0,999);
			$qr_code_url="http://".$_SERVER['HTTP_HOST']."/index/pay/qrcode_pay?qr_code_number=".$code['qr_code_number'];
			$code['qr_code_url'] = $qr_code_url;
			$code['qr_code_time'] = now_time();
			$code['qr_code_status'] = 1;
			$code['status'] = 1;
			$res = db('agent_qr_code')->insert($code);
		} 
		//判断生成数量是否相等
		if(($x-1)==$code_number){
			return json(['code'=>200,'msg'=>'添加成功','data'=>$code]);
		}else{
			return json(['code'=>402,'msg'=>'添加失败']);
		}
		}
    	return $this->fetch();
	}


	//商家绑定二维码
	public function agent_add_qr_code()
    {
		$agent_id=input('agent_id');
		//判断等级
		$regional_id=session('d_id');
		$regional = db('info_oem')->where('id',$regional_id)->find();              //区域运营商
		if($regional['user_level']==3){
		$info_oem = db('info_oem')->where('id',$regional['agency_id'])->find();    //省市代理
	     }
		if(request()->isPost()){
		$code_number=trim(input('code_number'));

		// //查询区域运营商信息
		// $info_ome = db('info_oem')->field('id,agency_id')->where('id',session('d_id'))->find();
		//查询省市级代理信息
		//$info_agency = db('info_oem')->where('id',$regional['agency_id'])->find();
		
       //查询二维码信息
		$agent_qr_code = db('agent_qr_code')->where('qr_code_number',$code_number)->find();
	   //查询要绑定的商家
		$info_agent = db('info_agent')->where('id',$agent_id)->find();

        //判断编号是否存在
		if(!$agent_qr_code){
			return json(['code'=>402,'msg'=>'抱歉！该编号不存在！']);
		}

		// //判断编号是否在该代理下面
		// if($info_agency['cb_no']!==$agent_qr_code['cb_no']){
		// 	return json(['code'=>402,'msg'=>'抱歉!该编号属于其他代理<br/>请查看编号是否正确']);
		// }

		// //判断编号是否在该代理下面
		// if($regional_id!==$agent_qr_code['regional_id']){
		// 	return json(['code'=>402,'msg'=>'抱歉!该编号属于代理下的其他区域<br/>请查看编号是否填错']);
		// }


		//提示已绑定商家信息
		if($agent_qr_code['agent_id']){
			$info_agent_code = db('info_agent')->where('id',$agent_qr_code['agent_id'])->find();
			if($info_agent_code){
			return json(['code'=>402,'msg'=>'抱歉！该编号已绑定商家:'.$info_agent_code['agent_name']."<br/>手机号:".$info_agent_code['mobile']]);
			}
		}
		
		//绑定二维码编号
		$codearr['agent_id']=$info_agent['id'];
		$codearr['agent_name']=$info_agent['agent_name'];

		$codearr['regional_id']=$regional['id'];
		$codearr['regional_name']=$regional['user_name'];
		
		$codearr['oem_id']=$info_oem['id'];
		$codearr['oem_name']=$info_oem['user_name'];
		$codearr['cb_no']=$info_oem['cb_no'];

		//$codearr['agent_mobile']=$info_agent['mobile'];
		$codearr['qr_code_status']=2;
		$codearr['qr_code_update_time']=now_time();
		$ress = db('agent_qr_code')->where('id',$agent_qr_code['id'])->update($codearr);
		  
		if($ress){
			return json(['code'=>200,'msg'=>'绑定成功']);
		}else{
			return json(['code'=>402,'msg'=>'绑定失败']);
		}
		}
		$agent_qr_code_number = db('agent_qr_code')->field('id,qr_code_number')->where('agent_id',$agent_id)->select();	
		$this->assign('agent_qr_code_number',$agent_qr_code_number);
		$this->assign('agent_id',$agent_id);
		$this->assign('regional',$regional);
		
		//$this->assign('info_ome',$info_ome);
    	return $this->fetch();
	}

	//商家改变状态
	public function code_status()
    {
    	$where['status'] = input('status');
    	$ress = db('agent_qr_code')->where('id',input('id'))->update($where);
    	if($ress){
			return json(['code'=>200,'msg'=>'成功']);
		}else{
			return json(['code'=>402,'msg'=>'失败']);
		}
	}
	
	//二维码解绑
	public function code_jiebang()
    {
		$where['qr_code_status'] = 1;
		$where['agent_id'] = "";
		$where['cb_no'] = "";
		$where['status'] = 1;
		$where['agent_name'] = "";
		$where['qr_code_update_time'] = "";
		$where['regional_id'] = "";
		$where['regional_name'] = "";
		$where['oem_id'] = "";
		$where['oem_name'] = "";
    	$ress = db('agent_qr_code')->where('id',input('id'))->update($where);
    	if($ress){
			return json(['code'=>200,'msg'=>'成功']);
		}else{
			return json(['code'=>402,'msg'=>'失败']);
		}
    }


	//下载批量生成的二维码中的单个商家二维码。
	public function save_qr_code()
    {   
		$agent_code = db('agent_qr_code')->where('id',input('id'))->find(); 
		$this->assign('agent_code',$agent_code);
    	return $this->fetch();
	}
	
	//批量选择所要下载的二维码
    public function down_qr_code(){
		$qr_id = input('id');
		$qr_id = substr($qr_id,0,strlen($qr_id)-1);
		$arr_id = explode(",", $qr_id); 
		$qr_arr = array();
		if(count($arr_id)>0){
			for($i=0;$i<count($arr_id);$i++){
				//获取商品信息
				$agent_code = db('agent_qr_code')->where('id',$arr_id[$i])->find();
				array_push($qr_arr,$agent_code);
			}
		}else{
			return json(["code"=>403,'msg'=>'请选择商品']);
		}
		$this->assign("qr_arr",$qr_arr);
		
    	return $this->fetch();
	}

    //批量打包下载
	public function down_zip(){
		$oem_id=session('d_id');
		$datalist=array();
		$filename = "././public/upload/{$oem_id}_qr.zip";
		$length=input("length");
		if(file_exists($filename)){
			unlink($filename);
		}
		 $zip = new \ZipArchive();
		 if ($zip->open($filename, \ZipArchive::CREATE)==TRUE) {
		  for( $i=0;$i<$length;$i++){
		  	$s=$oem_id."_".$i;
		  	$val="././public/upload/".$s.".png";
		   if(file_exists($val)){
		    $zip->addFile( $val, basename($val));
		   }
		  }
		  $zip->close();
		 }
		
		if(!file_exists($filename)){
		 exit("无法找到文件");
		}
		header("Cache-Control: public");
		header("Content-Description: File Transfer");
		header('Content-disposition: attachment; filename='.basename($filename)); //文件名
		header("Content-Type: application/zip"); //zip格式的
		header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
		header('Content-Length: '. filesize($filename)); //告诉浏览器，文件大小
		@readfile($filename);
	}
	
	//批量图片制作
	public function export_img(){
		$imgs=input()['imgs'];
		$oem_id=session('d_id');
		foreach($imgs as $k=>$v){
			$s=$oem_id."_".$k;
			$path="././public/upload/".$s.".png";
			$this->base64_image_content($v, $path);
		}
		exit;
		
		//var_dump($_POST);exit;
	}

	//图片转成64进制
	function base64_image_content($base64_image_content,$path){
	    //匹配出图片的格式
	    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
	        $type = $result[2];
	        if (file_put_contents($path, base64_decode(str_replace($result[1], '', $base64_image_content)))){
	            return '/'.$path;
	        }else{
	            return false;
	        }
	    }else{
	        return false;
	    }
	}

	//省级代理列表
    public function agency_id()
    {
		$user_level=session("user_level");
		//平台
		if($user_level==1){
			$where['a.oem_id']=session('d_id');
		}
		//省级代理
		if($user_level==4){
			$where['a.province_id']=session('d_id');
		}		
		//查询省代下市代数量
		$map['user_level'] = 2;
		$map['user_type'] = 1;
		$map['oem_id'] = 1;
		$city = db('info_oem')->field('count(id) as count,province_id')->where($map)->group('province_id')->buildSql();
		
		$where['user_level']=4;
    	$list=db('info_oem')->alias('a')		
		->join($city.'b','b.province_id = a.id','LEFT')
		->field('a.id,a.address,a.oem_pt,a.user_name,a.province,a.mobile,a.balance,a.commission,a.score,a.is_verify,a.status,a.add_time,a.oem_bili,a.s_score,a.oem_city,a.oem_level,a.ome_agent_id,a.sc_bili,b.count')
    	->where($where)
		->order('a.add_time desc')
    	->paginate(10);
		$this->assign("list",$list);
		$this->assign('empty','<span class="empty" style="margin-top:5%">没有数据</span>');
    	return $this->fetch();
	}

	//市级代理列表
    public function agency_id1()
    {
		$user_level=session("user_level");

		//平台
		if($user_level==1){//oem
			$where['a.oem_id']=session('d_id');
		}
		//省代理
		if($user_level==4){
			$where['a.province_id']=session('d_id');
		}

		//查询市代下区域运营商数量
		$map['user_level'] = 3;
		$map['user_type'] = 1;
		$map['oem_id'] = session('d_id');
		$city = db('info_oem')->field('count(id) as count,agency_id')->where($map)->group('agency_id')->buildSql();
		
		$user_name="";
		$mobile="";
		$province_id="";

		//根据用户名查找区域运营商
		if(input('user_name')){
			$where['a.user_name'] = ['like','%'.input('user_name').'%'];
			$user_name = input('user_name');
		}
		
		//根据手机号查找区域运营商
		if(input('mobile')){
			$where['a.mobile'] = ['like','%'.input('mobile').'%'];
			$mobile = input('mobile');
		}

		//根据省代理查找市代理
		if(input('province_id')){
			$where['a.province_id'] = input('province_id');
			$province_id = input('province_id');
		}
		
		$where['user_level']=2;
    	$list=db('info_oem')->alias('a')		
		->join($city.'b','b.agency_id = a.id','LEFT')
		->field('a.id,a.address,a.oem_pt,a.user_name,a.province_id,a.province,a.city,a.mobile,a.balance,a.commission,a.score,a.is_verify,a.status,a.add_time,a.oem_bili,a.s_score,a.oem_city,a.oem_level,a.ome_agent_id,b.count')
    	->where($where)
		->order('a.add_time desc')
    	->paginate(10);
		$this->assign("list",$list);
		$this->assign('empty','<span class="empty" style="margin-top:5%">没有数据</span>');

		//获取省代理列表
		if($user_level==1){
			$province = db('info_oem')->field('id,user_name')->where(['user_level'=>4])->select();
			$this->assign('province',$province);
		}
        $this->assign('province_id',$province_id);
		$this->assign('user_name',$user_name);
		$this->assign('mobile',$mobile);

    	return $this->fetch();
	}

	//区域运营商列表
    public function agency_id2()
    {
		$user_level=session("user_level");
		if($user_level==1){//oem
			$where['a.oem_id'] = session('d_id');
			$wheres['oem_id'] = session('d_id');
		}
		if($user_level==2){//市代理
			$where['a.agency_id'] = session('d_id');
		}
		if($user_level==4){//省代理
			$where['a.province_id'] = session('d_id');
			$wheres['province_id'] = session('d_id');
		}
		
		$province_id="";
		$user_name="";
		$mobile="";
		$agency_id="";

		//根据省代理商查找区域运营商
		if(input('province_id')){
			$where['a.province_id'] = input('province_id');
			$province_id = input('province_id');
		}
		
		//根据用户名查找区域运营商
		if(input('user_name')){
			$where['a.user_name'] = ['like','%'.input('user_name').'%'];
			$user_name = input('user_name');
		}
		
		//根据手机号查找区域运营商
		if(input('mobile')){
			 $where['a.mobile'] = ['like','%'.input('mobile').'%'];
			$mobile = input('mobile');
		}

		//根据市代理商查找区域运营商
		if(input('agency_id')){
			$where['a.agency_id'] = input('agency_id');
			$agency_id = input('agency_id');
		}

		//推广的专员
		$where_pt['is_pt1']=1;
		$agentcount = db('info_user')->field('count(is_pt1) as count,agency_id2')->where($where_pt)->group('agency_id2')->buildSql();		
		
		$where['a.user_level']=3;
		$field = 'a.*,t.user_name as tname,b.count';
    	$list = Db::name("info_oem")->alias('a')
    	->join($agentcount.'b','b.agency_id2 = a.id','LEFT')
		->join('info_oem t','t.id = a.agency_id','LEFT')
		->field($field)->where($where)
		->order('a.add_time desc')
		->paginate(10,false,['query'=>request()->param()]);
    	
		$this->assign("list",$list);
		$this->assign('empty','<span class="empty" style="margin-top:5%">没有数据</span>');
		
		//获取市代理列表
		if($user_level==1 || $user_level==4){
			$agency = db('info_oem')->field('id,user_name')->where($wheres)->where(['user_level'=>2])->select();
			$this->assign('agency',$agency);
		}
		
		//获取省代理列表
		if($user_level==1){
			$province = db('info_oem')->field('id,user_name')->where($wheres)->where(['user_level'=>4])->select();
			$this->assign('province',$province);
		}

		$this->assign('province_id',$province_id);
		$this->assign('user_name',$user_name);
		$this->assign('mobile',$mobile);
		$this->assign('agency_id',$agency_id);
    	return $this->fetch();
	}
	
    //业务员
    public function salesman()
    {
    	$user_level=session("user_level");
		if($user_level==1){//oem
			$where['oem_id']=session('d_id');
		}elseif($user_level==2){//省代理
			$where['agency_id1']=session('d_id');
		}elseif($user_level==3){
			$where['agency_id2']=session('d_id');
		}
    	$list=db('info_salesman')->where($where)->select();
		$this->assign("list",$list);
		$this->assign('empty','<span class="empty" style="margin-top:5%">没有数据</span>');
    	return $this->fetch();
	}
	
	//添加商家
	public function add_agent(){
		if(request()->isPost()){
			$is_reg=db('info_agent')->where("mobile",input("mobile"))->find();
			if($is_reg){
				return json(['code'=>402,'msg'=>'添加失败,该联系电话已经添加过商家']);
			}
			$cut_infor_oem = db('info_oem')->where("id",session('d_id'))->find();
			
			$is_userreg=db('info_user')->where("mobile",input("usermobile"))->find();			
			if(!$is_userreg){
				return json(['code'=>402,'msg'=>'添加失败,该手机号码不是会员']);
			}
			$param['city_pt']=$is_userreg['tj_pt1'];
			$is_regs=db('info_agent')->where("user_id",$is_userreg['id'])->find();
			if($is_regs){
				return json(['code'=>402,'msg'=>'添加失败,该会员已经添加过商家']);
			}
			
			//市场专员手机号码
			$sc = db('info_user')->where("mobile",input("scmobile"))->where('is_pt1',1)->find();			
			if(!$sc){
				return json(['code'=>402,'msg'=>'添加失败,该手机号不是市场专员手机号']);
			}
	
            $param['sc_id'] 	= $sc['tj_pt1'];						
			$param['user_id'] 	= $is_userreg['id'];
			$param['add_time'] 	= now_time();
			$param['mobile'] 	= input("usermobile");
			$param['agent_name'] 	= input("agent_name");
			$param['user_name'] 	= input("user_name");
			$param['logo']	= input("thumb");
			$param['store_property'] 	= input("store_property");
			$param['password'] = md5_salt("123456");
			$param['operation_pwd'] 	= md5_salt("123456");
			$param['oem_id']	=  1;
			$param['agency_id'] = $cut_infor_oem['province_id'];
			$param['agency_id1'] = $cut_infor_oem['agency_id'];
			$param['agency_id2'] =  $cut_infor_oem['id'];
			$param['is_state'] = 1;
			$param['trade_type'] = input("trade_type");
			$param['trade_type2'] = input("trade_type2");
			$param['is_score'] = 1;   //添加商家默认开启鼓励金营销
			$oem1=db('info_oem')->where("id",$cut_infor_oem['agency_id'])->find();
			//签约信息
			$param['cb_no'] 		=  $oem1['cb_no'];
			$param['cb_miyao'] 		=  $oem1['cb_miyao'];
			$param['cb_login_name'] =  input("cb_login_name");
			$param['cb_clerk'] 		=  input("cb_clerk");
			$param['cb_huilu'] 		=  input("cb_huilu");
			$res = db('info_agent')->insert($param);
	
			if($res){
				$agent_id= Db::name('info_agent')->getLastInsID();
				$data['agent_id']=$agent_id;
				$data['oem_id']=session('oem_id');
				$data['store_name']=input("agent_name");
				$data['add_time']=now_time();
				db('agent_store')->insert($data);
				
				//修改用户  建立门店  修改关系				
				$update['is_agent']=2;
				$update['tj_agent']=$agent_id;
				db('info_user')->where('id',$is_userreg['id'])->update($update);
				

				//银行结算信息
				$params['trade_type'] 		= input("trade_type");
				$params['trade_type2'] 		= input("trade_type2");
				$params['agent_name1'] 		= input("agent_name");
				$params['account_name'] 	= input("account_name");
				$params['bank_account'] 	= input("bank_account");
				$params['open_bank'] 		= input("open_bank");
				$params['yl_mobile'] 		= input("yl_mobile");
				$params['branch_address'] 	= input("branch_address");
				$params['branch_name'] 		= input("branch_name");
				$params['agent_id'] 		= $agent_id;
				$params['state'] 			= 1;
				$result1 = db('agent_qianyue')->insert($params);

        			
				return json(['code'=>200,'msg'=>'添加成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'添加失败']);
			}
    	}
		$typelist = db('sys_platform_type')->where('pid',0)->select();
		$this->assign('typelist',$typelist);
    	return $this->fetch();
	}

	//添加省代
    public function add_agency(){
    	if(request()->isPost()){
			$is_reg=db('info_oem')->where("mobile",input("mobile"))->find();
			if($is_reg){
				return json(['code'=>402,'msg'=>'添加失败,该手机号码已经添加过']);
			}
			$param['add_time'] 		= now_time();
			$param['mobile'] 		= input("mobile");
			$param['province'] 		= input("province");
			$param['user_name'] 	= input("user_name");
			$param['password'] 		= md5_salt(input("password"));
			$param['operation_pwd'] = md5_salt(input("operation_pwd"));
			$param['status'] 		= input("status");
			$param['user_level']  	= 4;
			$param['oem_bili']  	= input("oem_bili");
			$param['oem_id'] 		= session('d_id');
		
			$res = db('info_oem')->insert($param);
			if($res){
				return json(['code'=>200,'msg'=>'添加成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'添加失败']);
			}
    	}
    	return $this->fetch();
	}

	//添加市代
    public function add_agency1(){
		$user_level=session('user_level');
    	if(request()->isPost()){
			$is_reg=db('info_oem')->where("mobile",input("mobile"))->find();
			if($is_reg){
				return json(['code'=>402,'msg'=>'添加失败,该手机号码已经添加过']);
			}
			$param['add_time'] 		= now_time();
			$param['province'] 		= input("province");
			$param['province_id'] 	= input("province_id");
			$param['city'] 			= input("city");
			$param['mobile'] 		= input("mobile");
			$param['user_name'] 	= input("user_name");
			$param['password'] 		= md5_salt(input("password"));
			$param['operation_pwd'] = md5_salt(input("operation_pwd"));
			$param['user_level']  	= 2;
			$param['cb_no']  		= trim(input('cb_no'));
			$param['cb_miyao'] 		= input("cb_miyao");
			$param['oem_id'] 		= session('d_id');
			$param['s_score'] 	    = input("s_score");
			$param['oem_level'] 	= input("oem_level");
			$param['oem_bili'] 	    = input("oem_bili");
			$param['status'] 		= input("status");
			$res = db('info_oem')->insert($param);
			if($res){
				return json(['code'=>200,'msg'=>'添加成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'添加失败']);
			}
		}
		if($user_level==1){
			$reg=db('info_oem')->field('id,user_name,province,oem_bili')->where("user_level",4)->select();
			$this->assign('province',$reg);
		}
    	return $this->fetch();
	}
	
    //添加业务员
    public function add_manager(){
    	if(request()->isPost()){
			$is_reg=db('info_salesman')->where("mobile",input("mobile"))->find();
			if($is_reg){
				return json(['code'=>402,'msg'=>'添加失败,该手机号码已经添加过']);
			}
			
			$cut_infor_oem = db('info_oem')->where("id",session('d_id'))->find();
			$param['add_time'] 		= now_time();
			$param['mobile'] 		= input("mobile");
			$param['name'] 			= input("name");
			$param['oem_id']		= $cut_infor_oem['oem_id'];
			$param['agency_id1']	= $cut_infor_oem['agency_id'];
			$param['agency_id2']	= $cut_infor_oem['id'];
			$res = db('info_salesman')->insert($param);
			if($res){
				return json(['code'=>200,'msg'=>'添加成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'添加失败']);
			}
			
    	}
    	return $this->fetch();
	}

	
    //修改省级代理
	public function edit_agency(){
		if(request()->isPost()){
			$param['update_time'] 	= now_time();
			$param['province'] 		= input("province");                //省代关联省份
			$param['mobile'] 		= input("mobile");
			$param['user_name'] 	= input("user_name");
			if(input("password")){
				$param['password'] 	= md5_salt(input("password"));
			}
			if(input("operation_pwd")){
				$param['operation_pwd'] = md5_salt(input("operation_pwd"));
			}
			$param['status'] 		= input("status");
			$param['oem_bili'] 		= input("oem_bili");
			$param['id'] 			= input("id");
			$res = db('info_oem')->update($param);
			if($res){
				return json(['code'=>200,'msg'=>'修改成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
    	}
		$account=db('info_oem')->find(input("id"));
		$this->assign('ad',$account);
		return $this->fetch();
	}

	//修改市级代理
	public function edit_agency1(){
		if(request()->isPost()){
			$param['update_time'] 	= now_time();
			$param['province'] 		= input("province");
			$param['city'] 			= input("city");
			$param['mobile'] 		= input("mobile");
			$param['user_name'] 	= input("user_name");
			$param['province_id'] 	= input("province_id");
			$param['oem_bili'] 		= input("oem_bili");
			if(input("password")){
				$param['password'] 	= md5_salt(input("password"));
			}
			if(input("operation_pwd")){
				$param['operation_pwd'] = md5_salt(input("operation_pwd"));
			}
			$param['status'] 	= input("status");
			$param['cb_no']  	= trim(input("cb_no"));
			$param['cb_miyao'] 	= input("cb_miyao");
			$param['oem_level'] = input("oem_level");               //代理等级，1正式，2自营
			$param['s_score'] 	= input("s_score");                 //不同代理下新会员所得鼓励金

			$param['id'] = input("id");
			$province_id = db('info_oem')->where('id',input("id"))->value('province_id');
			
			if($province_id!==intval($param['province_id'])){
			//修改省代时，区域跟随变化
            $oem_param['province_id']=input("province_id");
			$where_oem['agency_id'] = input("id");
			$oem_count = db('info_oem')->where($where_oem)->count('id');
			if($oem_count>0){
				$oem_res = db('info_oem')->where($where_oem)->update($oem_param);
				if(!$oem_res){
					return json(['code'=>402,'msg'=>'修改区域失败','data'=>$oem_param]);
				}
		   	}
			
			//修改省代时，商家跟随变化
			$agent_param['agency_id']=input("province_id");
			$where_agent['agency_id1'] = input("id");
			$agent_count = db('info_agent')->where($where_agent)->count('id');
			if($agent_count>0){
				$agent_res = db('info_agent')->where($where_agent)->update($agent_param);
				if(!$agent_res){
					return json(['code'=>402,'msg'=>'修改商家失败','data'=>$agent_param]);
				}
			}

			//修改省代时，会员与市场专员也跟随变化
			$user_param['agency_id']=input("province_id");
			$where_user['agency_id1'] = input("id");
			$user_count = db('info_user')->where($where_user)->count('id');
			if($user_count>0){
				$user_res = db('info_user')->where($where_user)->update($user_param);
				if(!$user_res){
					return json(['code'=>402,'msg'=>'修改会员失败','data'=>$user_param]);
				}
			}
			 
		}

		    //修改省代时，市代跟随变化（必须最后修改，不然重新提交了也没用）
		    $res = db('info_oem')->update($param);
			if(!$res){
				return json(['code'=>402,'msg'=>'修改代理失败','data'=>$param]);
			}else{
				return json(['code'=>200,'msg'=>'修改成功','data'=>$param]);
			}
		}
		$account=db('info_oem')->find(input("id"));
		$province = db('info_oem')->field('id,user_name,province,oem_bili')->where("user_level",4)->select();
		$this->assign('province',$province);
		$this->assign('ad',$account);
		return $this->fetch();
	}

	//修改区域运营商、平台、省代、市代都能修改
    public function edit_agency2(){

		//读取当前区域信息
		$account=db('info_oem')->find(input("id"));
		$user_level=session('user_level');
		if(request()->isPost()){
			$param['update_time'] 		= now_time();
			$param['id'] 				= input("id");
			$param['province'] 			= input("province");
			$param['city'] 				= input("city");
			$param['area'] 				= input("area");
			$param['mobile'] 			= input("mobile");
			$param['user_name'] 		= input("user_name");
			if(input("password")){
				$param['password'] 		= md5_salt(input("password"));
			}
			$param['oem_bili'] 			= input("oem_bili");
			$param['status'] 			= input("status");

			if(input("agency_id")){
				$param['agency_id'] 	= input("agency_id");
				$area_oem = db('info_oem')->find($param['agency_id']);
				$param['province_id'] 	= $area_oem['province_id'];

				//当代理改变时，区域运营商和下面的层级一起变化
				if($account['agency_id']!==intval($param['agency_id'])){

					//修改省代时，商家跟随变化
					$agent_param['agency_id'] = $area_oem['province_id'];
					$agent_param['agency_id1'] = $param['agency_id'];
					$where_agent['agency_id1'] = $param['id'];
					//区域下是否存在商家
					$agent_count = db('info_agent')->where($where_agent)->count('id');
					if($agent_count>0){
						$agent_res = db('info_agent')->where($where_agent)->update($agent_param);
						if(!$agent_res){
							return json(['code'=>402,'msg'=>'修改商家信息失败','data'=>$agent_param]);
						}
					}

					//修改省代时，会员与市场专员也跟随变化
					$user_param['agency_id']=input("province_id");
					$user_param['agency_id1'] = $param['agency_id'];
					$where_user['agency_id1'] = $param['id'];
					//区域下是否存在会员
					$user_count = db('info_user')->where($where_user)->count('id');
					if($user_count>0){
						$user_res = db('info_user')->where($where_user)->update($user_param);
						if(!$user_res){
							return json(['code'=>402,'msg'=>'修改会员信息失败','data'=>$user_param]);
						}
					}
				}
			}
			$res = db('info_oem')->update($param);
			if($res){
				return json(['code'=>200,'msg'=>'修改成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
		}
		$province=array();
		//获取市代列表
        if($user_level==1){
			$province = db('info_oem')->field('id,user_name,oem_bili')->where('user_level',2)->select();
		}

		if($user_level==4){
			$where_area['user_level']=2;
			$where_area['province_id']=session('d_id');
			$province = db('info_oem')->field('id,user_name,oem_bili')->where($where_area)->select();
		}

		$this->assign('province',$province);
		//查询区域对应代理
		$infor_oem=db('info_oem')->find($account['agency_id']);
		$this->assign('ad',$account);
		$this->assign('lev',$infor_oem);
		return $this->fetch();
	}

	//添加区域,只有代理能添加区域
	public function add_agency2(){
		$user_level=session('user_level');
		$d_id=session('d_id');
		if(request()->isPost()){
			$is_reg=db('info_oem')->where("mobile",input("mobile"))->find();
			if($is_reg){
				return json(['code'=>402,'msg'=>'添加失败,该手机号码已存在']);
			}
			$cut_infor_oem = db('info_oem')->where("id",$d_id)->find();
			$param['add_time'] 		= now_time();
			$param['mobile'] 		= input("mobile");
			$param['province_id'] 	= $cut_infor_oem['province_id'];
			$param['province'] 		= input("province");
			$param['city'] 			= input("city");
			$param['area'] 			= input("area");
			$param['user_name'] 	= input("user_name");
			$param['password'] 		= md5_salt(input("password"));
			$param['oem_bili'] 		= input("oem_bili");
			$param['status'] 		= input("status");
			$param['user_level']  	= 3;
			$param['oem_id']		= 1;
			$param['agency_id']	    = $d_id;

			$res = db('info_oem')->insertGetId($param);      //获取当前插入的主键
			// $res= Db::name('info_oem')->getLastInsID();   //获取最后一条主键
			if($res){
				$is_userreg=db('info_user')->where("mobile",input("mobile"))->find();
				if($is_userreg){
					$datas['agency_id']  = $cut_infor_oem['province_id'];
					$datas['agency_id1'] = $d_id;
					$datas['agency_id2'] = $res;
					$datas['is_city'] 	 = $res;
					$datas['is_fx'] 	 = 1;
					$datas['level'] 	 = $is_userreg['id'];
					if($is_userreg['is_agent']==2){
						$agent_info = db('info_agent')->where("user_id",$is_userreg['id'])->find();
						$datas['tj_agent'] 	= $agent_info['id'];
						$datas['is_pt']=0;
						$datas['tj_pt']=0;
						$datas['is_pt1']=0;
						$datas['tj_pt1']=0;
					}
					$user = db('info_user')->where('id',$is_userreg['id'])->update($datas);
					if(!$user){
					    return json(['code'=>402,'msg'=>'识别该手机号对应商家会员信息失败','data'=>$datas]);
				    }	
				}
			}else{
				return json(['code'=>402,'msg'=>'添加失败']);
			}
            return json(['code'=>200,'msg'=>'添加成功','data'=>$param]);
    	}
		
		//获取当前市代的分佣比例
		$oem = db('info_oem')->where('id',session('d_id'))->find();
		$this->assign('oem',$oem);
    	return $this->fetch();
	}
	
	//联盟商圈审核
	public function union_sh(){
		
		if(request()->isPost()){
    		$param=input('post.');
			if(!empty($param['store_name']))$where['a.name'] = ['like','%'.$param['store_name'].'%'];
			if(!empty($param['state']))$where['a.state'] = $param['state'];
    	}
    	$where['a.oem_id'] = session('d_id');
    	$list = Db::table('union_agent')
    	->alias('a')
		->field('a.id,a.sq_name,a.address,a.name,a.tel,a.state,a.is_state,b.user_name')
    	->join('info_user b','a.u_id = b.id')
    	->where($where)
    	->order('a.add_time desc')
    	->paginate(20);
        $this->assign('list',$list);
        $this->assign('empty','<span class="empty" style="margin-top:5%">没有数据</span>');
    	return $this->fetch();
	}
	
	//联盟商圈审核
	public function union_shenhe(){
    	$param['state'] = input("lid");
    	$list = Db::table('union_agent')->where('id',input("id"))->update($param);
    	if($list){
			return json(['code'=>200,'msg'=>'成功']);
		}else{
			return json(['code'=>402,'msg'=>'失败']);
		}
	}
	//业务员推广二维码
	public function tuiguang(){
    	$data = Db::table('info_salesman')->where('id',input("id"))->find();
		//二维码链接
    	$redirect_url="http://".$_SERVER['HTTP_HOST']."/index/index/regist?fromuid=3".
    	"&oem_id=".$data['oem_id']."&salesman_id=".$data['id'];
		$data['redirect_url'] = $redirect_url;
    	
    	$this->assign('data',$data);
    	return $this->fetch();
	}
	
	
    //商家导出
    public function agent_dcxml(){
	 	$param = input('post.');
		$query=[];
		//商家
		if(input('agent_name')){
			$query['a.agent_name'] = input('agent_name');
			$this->assign("agent_name",input("agent_name"));
			$where['a.agent_name'] = ['like', '%'.input('agent_name').'%'];
		}else{
			$this->assign("agent_name",'');
		}
		if(input('mobile')){
			$query['a.mobile'] = input('mobile');
			$this->assign("mobile",input("mobile"));
			$where['a.mobile'] = input('mobile');
		}else{ 
			$this->assign("mobile",'');
		}
		if(session('user_level')==1){
			$where['a.oem_id'] = session('d_id');
		}elseif(session('user_level')==2){
			$where['a.agency_id1'] = session('d_id');
		}else{
			$where['a.agency_id2'] = session('d_id');
		}
		
		if(input('cm')){  
			$where['u.mobile'] = input('cm'); 
		}
		
		if(session('user_level')==1 || session('user_level')==2){
			if(input('ch_city')){ 
				$where['a.agency_id2'] = input('ch_city'); 
			}
		}
		
		if(session('user_level')==1){
			if(input('operator')){ 
				$where['a.agency_id1'] = input('operator'); 
			}
		}
		
		//排序
		$order = 'a.add_time desc'; 
		if(input('order')){
			if(input('order') == 1){
				//鼓励金排序
				$order = 'a.score desc';
			}else{
				//推广数
				$order = 'b.count desc';
			}
		}
		
		//推广
		$tjagent = db('info_user')->field('count(id) as count,tj_agent')->group('tj_agent')->buildSql();
		//合伙人
		$puuser = db('info_user')->field('count(id) as counts,tj_agent')->where('is_pt',1)->group('tj_agent')->buildSql();
		
    	$list=db('info_agent')->alias('a')		
		->join($tjagent.'b','b.tj_agent = a.id','LEFT')
		->join($puuser.'c','c.tj_agent = a.id','LEFT')
		->join('info_oem d','a.agency_id2 = d.id','LEFT')
		->join('info_user u','u.id=a.sc_id','LEFT')
		->where($where)->order('a.add_time desc')
		->field('a.id,a.agent_name,a.mobile,a.balance,a.score,a.store_property,a.address,a.is_state,a.status,a.add_time,b.count,c.counts,d.user_name as city_name')
		->select();
		$str ="店铺名称,服务商,手机号码,余额,鼓励金,资质认证,推广数,状态,创建时间,"."\n";
        $str = iconv('utf-8','gbk',$str);
        foreach($list as $k=>$row){
        	$agent_name = iconv('utf-8','gbk',$row['agent_name']);
			$tel = iconv('utf-8','gbk','	'.$row['mobile']);
			$city_name = iconv('utf-8','gbk','	'.$row['city_name']);
			//$sex = iconv('utf-8','gbk',$row['sex']);
			//$nick_name = utf8ToGbk($row['nick_name']);
			$balance = iconv('utf-8','gbk','	'.$row['balance']);
			$score = iconv('utf-8','gbk','	'.$row['score']);
			/*if($row['store_property']==1){
				$property = '个人';
			}elseif($row['store_property']==2) {
				$property = '企业';
			}else{
				$property = '个体户';
			}
			$propertyname = iconv('utf-8','gbk',$property); */
			//$address = iconv('utf-8','gbk',$row['address']);
			if($row['is_state']==1){
				$state = '已签约';
			}else{
				$state = '未签约';
			}
			$statename = iconv('utf-8','gbk',$state);
			$count = iconv('utf-8','gbk',$row['count'] ? $row['count']:0);
			$counts = iconv('utf-8','gbk',$row['counts'] ? $row['counts']:0);
			if($row['status']==1){
				$status = '正常';
			}else{
				$status = '冻结';
			}
			$statusname = iconv('utf-8','gbk',$status);
			$add_time = iconv('utf-8','gbk','	'.$row['add_time']);
			$str .= $agent_name.",".$city_name.",".$tel.",".$balance.",".$score.",".$statename.",".$count.",".$statusname.",".$add_time.","."\n"; //用引文逗号分开 
        } 

	  	$filename ='商家列表.csv';   //设置文件名  
    	
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str; 
        exit;
	}
	//会员导出
    public function user_dcxml(){
	 	$param = input('post.');
		$query=[];
		$where = [];
		if(input('mobile')){
			$query['mobile'] = input('mobile');
			$this->assign("mobile",input("mobile"));
			$where['a.mobile'] = input('mobile');
		}else{
			$this->assign("mobile",'');
		}
		if(session('user_level')==1){
			//$where['a.oem_id'] = session('d_id');
		}elseif(session('user_level')==2){
			$where['a.agency_id1'] = session('d_id');
		}else{
			$where['a.agency_id2'] = session('d_id');
		}
		
		if(input("user_no")){ 
			$where['a.id']=input("user_no"); 
		}
		
		
		if(input('ch_city')){ 
			$where['a.agency_id2'] = input('ch_city'); 
		}
		
		if(input('yys')){ 
			$where['a.agency_id1'] = input('yys'); 
		}
		
		if(input('agent_id')){ 
			$where['a.tj_agent'] = input('agent_id'); 
		}
		
		$level = db('info_user')->field('count(id) as count,level')->group('level')->buildSql();
		
    	$list=db('info_user')->alias('a')		
		->join($level.'b','b.level = a.id','LEFT')
		->join('info_oem c','a.agency_id2 = c.id','LEFT')
		->join("info_agent d","a.tj_agent=d.id",'LEFT')
		->join("info_user e","a.level=e.id",'LEFT')
		->field('a.id,a.user_name,a.mobile,a.balance,a.commission,a.score,a.status,a.add_time,b.count,c.user_name as city_name,d.agent_name,e.mobile as tmobile')
		->where($where)->order('a.add_time desc')->select();
		$str ="编号,手机号,会员名,区域运营商,商家,推荐人,余额,鼓励金,推广数,状态,注册时间,"."\n";
        $str = iconv('utf-8','gbk',$str);
        foreach($list as $k=>$row){
        	$id = iconv('utf-8','gbk',$row['id']);
			$mobile = iconv('utf-8','gbk','	'.$row['mobile']);
			$city_name = iconv('utf-8','gbk','	'.$row['city_name']);
			$agent_name = iconv('utf-8','gbk','	'.$row['agent_name']);
			$tmobile = iconv('utf-8','gbk','	'.$row['tmobile']);
			$user_name = iconv('utf-8','gbk//IGNORE',$row['user_name']?$row['user_name'] : '扫码会员');
			$balance = iconv('utf-8','gbk',$row['balance']);
			$commission = iconv('utf-8','gbk',$row['commission']);
			$score = iconv('utf-8','gbk',$row['score']);
			$count = iconv('utf-8','gbk',$row['count']?$row['count'] : 0);
			if($row['status']==1){
				$payname = '正常';
			}else {
				$payname = '冻结 ';
			}
			$typename = iconv('utf-8','gbk',$payname); 
			$add_time = iconv('utf-8','gbk','	'.$row['add_time']);
			$str .= $id.",".$mobile.",".$user_name.",".$city_name.",".$agent_name.",".$tmobile.",".$balance.",".$score.",".$count.",".$typename.",".$add_time.","."\n"; //用引文逗号分开 
        } 

	  	$filename ='会员列表.csv';   //设置文件名  
    	
        header("Content-type:text/csv"); 
        header("Content-Disposition:attachment;filename=".$filename); 
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
        header('Expires:0'); 
        header('Pragma:public'); 
        echo $str; 
        exit;
	}
	
    public function show_user(){
		$account=db('info_user')->find(input("id"));
		$this->assign('ad',$account);
		return $this->fetch();
	}
    
    
    function show_score(){
		$param=input();
		if(!empty($param['begin_time']) && !empty($param['end_time'])){
			$where['a.add_time'] = ['between time',[$param['begin_time'],$param['end_time']]];
		}
		
		
    	$user_type = input('type');
    	$score_change = [];
    	
    	if($user_type == 1){//服务商鼓励金
    		$base_name = 'log_oem_score';
    		$where['a.oem_id'] = input('id');		
    	}elseif($user_type == 2){//商家鼓励金
    		$base_name = 'log_agent_score';
    		$where['a.agent_id'] = input('id');
    		//获取商家赠送，抵扣鼓励金
    		$agent_add_score = db('log_agent_score')
    								->where('agent_id',input('id'))
    								->where('balance > 0')
    								->sum('balance');
    								
    		$agent_reduce_score = db('log_agent_score')
    								->where('agent_id',input('id'))
    								->where('balance < 0')
    								->sum('balance');
    		$score_change['add_score']  = $agent_add_score;
    		$score_change['reduce_score']  = $agent_reduce_score;
    		
    		
    	}elseif($user_type == 3){//会员鼓励金
    		$base_name = 'log_user_score';
    		$where['a.u_id'] = input('id');		
    	}
		$where['a.balance'] = ['<>',0];
    	$list=Db::table($base_name)->alias('a')
			    ->where($where)
				->order('a.add_time desc')
			    ->paginate(20,false,['query'=>request()->param()]);
			    
			    
		
        $this->assign('list',$list);
        $this->assign('id',input('id'));
        $this->assign('type',$user_type);
        $this->assign('begin_time',input('begin_time'));
        $this->assign('end_time',input('end_time'));
		$this->assign('score_change',$score_change);
		
		
		
		
		$sumbalance = db($base_name)->alias('a')->where($where)->sum('a.balance');
		$this->assign('sumbalance',$sumbalance);
		$this->assign('empty','<span class="empty" style="margin-top:5%">没有数据</span>');
    	return $this->fetch();
    }
    
    function show_member(){
    	//获取当前省代推广的市代
    	$agency_list = db('info_oem')->field('id,user_name,mobile,agency_id,add_time')->where('agency_id',input('id'))->select();
    	
    	//获取当前充值的鼓励金
		$province_cz = db('log_paylog')
						->alias('a')
						->field('sum(a.balance) as province_cz')
						->join('info_user b','a.uid = b.id','left')
						->where('a.state',2)
						->where('a.order_type',8)
						->where('b.agency_id1',input('id'))
						->select();
		
    	foreach($agency_list as $key=>&$value ){
    		
    		
    		//获取当前充值的鼓励金
			$city_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as city_cz')
							->join('info_user b','a.uid = b.id','left')
							->where('a.state',2)
							->where('a.order_type',8)
							->where('b.agency_id2',$value['id'])
							->select();
    		
    		//根据市代查找商家
    		$agent_list = db('info_agent')->field('id,agent_name,mobile,mobile,agency_id2,add_time')->where('agency_id2',$value['id'])->select();
    		
    		//根据商家查找会员
    		foreach($agent_list as $k=>&$v){
    			//获取当前充值的鼓励金
				$agent_cz = db('log_paylog')
								->alias('a')
								->field('sum(a.balance) as agent_cz')
								->join('info_user b','a.uid = b.id','left')
								->where('a.state',2)
								->where('a.order_type',8)
								->where('b.tj_agent',$v['id'])
								->select();
    			
    			$user_list = db('info_user')->field('id,no,mobile,nickname,tj_agent,total_nums,add_time')->where('tj_agent',$v['id'])->select();
				foreach($user_list as $list_key=>$list_value){
					if($list_value['total_nums']>0){
						//消费会员
						$consume_user[] = $list_value;
					}else{
						//推广会员
						$promote_user[] = $list_value;
					}
				}
				isset($promote_user)?$promote_user:$promote_user=0;
				isset($consume_user)?$consume_user:$consume_user=0;
				
				$v['develop_user'] 	= count($user_list);
				$v['promote_user'] 	= $promote_user;
				$v['consume_user'] 	= $consume_user;
				$v['agent_cz'] 		= $agent_cz[0]['agent_cz'];
    		}
    		$value['agent_list'] 	= $agent_list;
    		$value['develop_agent'] = count($agent_list);
    		$value['city_cz'] 		= $city_cz[0]['city_cz'];
    	}
    	
    	$this->assign('province_cz',$province_cz[0]['province_cz']);
    	$this->assign('member_list',$agency_list);
    	return $this->fetch();
    }
    
    function show_city_member(){
		//根据市代查找商家
		$agent_list = db('info_agent')->field('id,agent_name,mobile,mobile,agency_id2,add_time')->where('agency_id2',input('id'))->select();
		
		//获取当前充值的鼓励金
		$city_cz = db('log_paylog')
						->alias('a')
						->field('sum(a.balance) as city_cz')
						->join('info_user b','a.uid = b.id','left')
						->where('a.state',2)
						->where('a.order_type',8)
						->where('b.agency_id2',input('id'))
						->select();
		
		//根据商家查找会员
		foreach($agent_list as $k=>&$v){
			
			//获取当前充值的鼓励金
			$agent_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as agent_cz')
							->join('info_user b','a.uid = b.id','left')
							->where('a.state',2)
							->where('a.order_type',8)
							->where('b.tj_agent',$v['id'])
							->select();
			
			$user_list = db('info_user')->field('id,no,mobile,nickname,tj_agent,total_nums,add_time')->where('tj_agent',$v['id'])->select();
			foreach($user_list as $list_key=>&$list_value){
				//获取当前充值的鼓励金
				$user_cz = db('log_paylog')
								->field('sum(balance) as user_cz')
								->where('state',2)
								->where('order_type',8)
								->where('uid',$list_value['id'])
								->select();
				
				$list_value['user_cz'] = $user_cz[0]['user_cz'];
				
				if($list_value['total_nums']>0){
					//消费会员
					$consume_user[] = $list_value;
				}else{
					//推广会员
					$promote_user[] = $list_value;
				}
			}
			isset($promote_user)?$promote_user:$promote_user=0;
			isset($consume_user)?$consume_user:$consume_user=0;
			
			$v['develop_user'] 	= count($user_list);
			$v['promote_user'] 	= $promote_user;
			$v['consume_user'] 	= $consume_user;
			$v['agent_cz'] 		= $agent_cz[0]['agent_cz'];
		}
		
		$this->assign('city_cz',$city_cz);
    	$this->assign('agent_list',$agent_list);
    	return $this->fetch();
    }
    function agents_tg(){
    	$agentid = input('id');
		$order="a.add_time"; 
		$sql=db('info_user')->field("count(id) as tjs,level")->group("level")->buildSql();
		$sqlp=db('log_paylog_copy')->field("sum(balance) as czs,uid,sum(agent_score) as scs")->where("tj_agent_id",$agentid)->where("order_type=8")->group("uid")->buildSql();
    	$list = db('info_user')
			->alias('a')		
			->join('info_user c','c.id = a.level','LEFT')
			->join('info_agent d','d.id = a.tj_agent','LEFT')
			->join($sql.' f','f.level = a.id','LEFT')
			->join($sqlp.' p','p.uid = a.id','LEFT')
			->field('p.czs,p.scs,f.tjs,a.balance,a.score,a.id,a.nickname,a.mobile,a.is_verify,a.sex,a.add_time,c.mobile as smobile,d.agent_name')
			->where('a.tj_agent',$agentid)
			->order("$order desc")
			->paginate(15,false,['query'=>request()->param()]);
			
		$total_cz=db('log_paylog_copy')->where('tj_agent_id',$agentid)->where('order_type',8)->sum("balance");
		$this->assign('total_cz',$total_cz?$total_cz:0);
        $this->assign('list',$list);
    	return $this->fetch();
    }
    function show_agent_member(){
    	
		$param=input();
		if(!empty($param['begin_time']) && !empty($param['begin_time'])){
			$where['a.add_time'] = ['between time',[$param['begin_time'],$param['end_time']]];
			$where1['add_time'] = ['between time',[$param['begin_time'],$param['end_time']]];
//			$where2['add_time'] = ['between time',[$param['begin_time'],$param['end_time']]];
			$this->assign('begin_time',$param['begin_time']);
			$this->assign('end_time',$param['end_time']);
		}else{
			$this->assign('begin_time','');
			$this->assign('end_time','');			
		}

		//根据商家查找会员
		$where2['tj_agent'] = input('id');
		$user_list = db('info_user')
						->field('id,no,mobile,nickname,tj_agent,score,total_nums,add_time')
						->where($where2)
						->select();
		
		//获取当前充值的鼓励金
		$where['a.state'] = 2;
		$where['a.order_type'] = 8;
		$where['b.tj_agent'] = input('id');
		$agent_cz = db('log_paylog')
						->alias('a')
						->field('sum(a.balance) as agent_cz')
						->join('info_user b','a.uid = b.id','left')
						->where($where)
						->select();
		
		
		foreach($user_list as $list_key=>&$list_value){
				
			//获取当前充值的鼓励金
			$where1['state'] = 2;
			$where1['order_type'] = 8;
			$where1['uid'] = $list_value['id'];
			$user_cz = db('log_paylog')
							->field('sum(balance) as user_cz')
							->where($where1)
							->select();
			$list_value['user_cz'] = $user_cz[0]['user_cz'];
				
			if($list_value['total_nums']>0){
				//消费会员
				$consume_user[] = $list_value;
			}else{
				//推广会员
				$promote_user[] = $list_value;
			}
		}
		isset($promote_user)?$promote_user:$promote_user=0;
		isset($consume_user)?$consume_user:$consume_user=0;
		
		$this->assign('id',input('id'));
		$this->assign('promote_user',$promote_user);
		$this->assign('consume_user',$consume_user);
    	$this->assign('user_number',count($user_list));
    	$this->assign('agent_cz',$agent_cz[0]['agent_cz']);
    	
    	return $this->fetch();
    }
    
    function show_user_member(){
    	
		//根据商家查找会员
		$user_list = db('info_user')
						->field('id,no,mobile,nickname,tj_agent,score,total_nums,add_time')
						->where('level',input('id'))
						->select();
		
		
		foreach($user_list as $list_key=>$list_value){
				
			if($list_value['total_nums']>0){
				//消费会员
				$consume_user[] = $list_value;
			}else{
				//推广会员
				$promote_user[] = $list_value;
			}
		}
		isset($promote_user)?$promote_user:$promote_user=0;
		isset($consume_user)?$consume_user:$consume_user=0;
		
		$this->assign('promote_user',$promote_user);
		$this->assign('consume_user',$consume_user);
    	$this->assign('user_number',count($user_list));
    	
    	return $this->fetch();
    }
    
    
    function show_ptuser_member(){
    	
		//根据商家查找会员
		$user_list = db('info_user')
						->field('id,no,mobile,nickname,tj_agent,score,total_nums,add_time')
						->where('level',input('id'))
						->select();
		
		
		foreach($user_list as $list_key=>$list_value){
				
			if($list_value['total_nums']>0){
				//消费会员
				$consume_user[] = $list_value;
			}else{
				//推广会员
				$promote_user[] = $list_value;
			}
		}
		isset($promote_user)?$promote_user:$promote_user=0;
		isset($consume_user)?$consume_user:$consume_user=0;
		
		$this->assign('promote_user',$promote_user);
		$this->assign('consume_user',$consume_user);
    	return $this->fetch();
    }
    
    function agent_score_detail(){
    	$type = input('type');
    	if($type == 1){		//鼓励金抵扣
    		$score_change = db('log_agent_score')
    						->where('agent_id',input('id'))
    						->where('balance > 0')
    						->paginate(20,false,['query'=>request()->param()]);
    	}else{//鼓励金赠送
    		$score_change = db('log_agent_score')
    						->where('agent_id',input('id'))
    						->where('balance < 0')
    						->paginate(20,false,['query'=>request()->param()]);
    		
    	}
    	$this->assign('list',$score_change);
    	
    	$this->assign('id',input('id'));
        $this->assign('type',$type);
    	$this->assign('begin_time',input('begin_time'));
    	$this->assign('end_time',input('end_time'));
        
    	return $this->fetch();
    }
     
	//商家申请列表
	public function agentsq(){
		$user_level=session("user_level");
		if($user_level==1){//oem
			$where['c.oem_id']=session('d_id');
		}elseif($user_level==2){//省代理
			$where['c.agency_id1']=session('d_id');
		}elseif($user_level==3){//市代理
			$where['c.agency_id2']=session('d_id');
		}
		if(input('contact_tel')){
			$where['a.contact_tel'] = input('contact_tel');
		}		
		if(input('agent_name1')){
			$where['a.agent_name1'] = ['like','%'.input('agent_name1').'%'];
		}
		
		$where['a.state'] = 2;
		$field="a.id,a.agent_name1,a.contacts,a.contact_tel,a.add_time,a.state";
		$list = db('agent_qianyue')->alias('a')				
				->join("info_user c","c.id=a.user_id",'inner')
				->where($where)
				->field($field)
				->order('a.add_time desc')
				->paginate(15,false,['query'=>request()->param()]);					

		$this->assign('list',$list);
		
		//获取运营中心列表
		$agency = db('info_oem')->field('id,user_name')->where('user_level',2)->select();
		$this->assign('agency',$agency);
		return $this->fetch();
	}
	
	//商家申请驳回
	public function agentbh(){
		$res=db('agent_qianyue')->where("id",input("id"))->update(["state"=>3]);
		if($res){
			return json(['code'=>200,'msg'=>'操作成功']);
		}else{
			return json(['code'=>404,'msg'=>'操作失败']);
		}
	}
	
	//商家编辑
	public function edit_agent(){
		$info_agent = db('info_agent')->find(input("id"));
		if(request()->isPost()){
			$info_oem = db('info_oem')->where('id',$info_agent['agency_id1'])->find();
			
			$param['id'] = input("id");						
			$param['agent_name'] 	= input("agent_name");
			$param['logo'] 			= input("logo");
			$param['user_name'] 	= input("user_name");
			$param['mobile'] 		= input("mobile");
			$param['trade_type'] 	= input("trade_type");
			$param['trade_type2'] 	= input("trade_type2");
			$param['agency_id1'] 	= input("agency_id1");
			$param['agency_id2'] 	= input("agency_id2");
			
			//密钥配置
			$param['cb_no'] 		=  $info_oem['cb_no'];
			$param['cb_miyao'] 		=  $info_oem['cb_miyao'];
			$param['cb_login_name'] =  input("cb_login_name");
			$param['cb_clerk'] 		=  input("cb_clerk");
			$param['cb_huilu'] 		=  input("cb_huilu");	

			$res = db('info_agent')->update($param);
			if($res){
				//银行结算信息
				$params['account_name'] 	= input("account_name");
				$params['bank_account'] 	= input("bank_account");
				$params['open_bank'] 		= input("open_bank");
				$params['yl_mobile'] 		= input("yl_mobile");
				$params['branch_address'] 	= input("branch_address");
				$params['branch_name'] 		= input("branch_name");
				$params['trade_type'] 		= input("trade_type");
				$params['trade_type2'] 		= input("trade_type2");
				$result1 = db('agent_qianyue')->where('user_id',$info_agent['user_id'])->update($params);	
				return json(['code'=>200,'msg'=>'修改成功','data'=>$param]);
			}else{
				return json(['code'=>402,'msg'=>'修改失败']);
			}
    	}

		$typelist=db('sys_platform_type')->where('pid',0)->select();
		$this->assign('typelist',$typelist);
		
		$this->assign('data',$info_agent);
		$list = db('agent_qianyue')->where('agent_id',$info_agent['id'])->find();
		$this->assign('ad',$list);
		
		if($list){
			$type2=db("sys_platform_type")->find($list['trade_type2']);
			$this->assign('type2',$type2);
		}else{
			$this->assign('type2',null);
		}
		
		//获取省代列表
		$province = db('info_oem')->field('id,user_name')->where('user_level',2)->select();
		$this->assign('province',$province); 
		 
		//获取区域运营商列表
		$yys = db('info_oem')->field('id,user_name')->where('user_level',3)->where('agency_id',$info_agent['agency_id1'])->select();
		$this->assign('yys',$yys);
		return $this->fetch();
	}
	
	/**
	 * 开通分享资格
	 * */
	public function is_share(){
		$where['is_fx'] = 1;
    	$ress = db('info_user')->where('id',input('id'))->update($where);
    	if($ress){
			return json(['code'=>200,'msg'=>'成功']);
		}else{
			return json(['code'=>402,'msg'=>'失败']);
		}
	} 
	

	//商家层级更改
	public function edit_agent_cj()
	{
		
		$id = input('id');

		$user_level = session('user_level');

		//获取用户信息
		$agent = db('info_agent')->where('id',$id)->field('agency_id,agency_id1,agency_id2,sc_id,id')->find();
		$this->assign('agent',$agent);

		$province_where['user_level']=4;
		$area_where['user_level']=2;
		$city_where['user_level']=3;

		if($user_level==4){//省级代理
			$province_where['province_id']=session('d_id');
		}

		if($user_level==2){//市级代理
			$area_where['agency_id']=session('d_id');
		}

		if($user_level==3){//区域代理
			$city_where['city_id']=session('d_id');
		}

		$province = db('info_oem')->field('id,user_name')->where($province_where)->select();
		$area = db('info_oem')->field('id,user_name')->where($area_where)->select();
		$city = db('info_oem')->field('id,user_name')->where($city_where)->select();

		$this->assign('province',$province);
		$this->assign('area',$area);
		$this->assign('city',$city);
		
		if(request()->isPost()){
			$data = input('post.'); 
			//修改商家下的会员
			$info_user = db('info_user')->where('tj_agent',$data['id'])->select();
			$user_arr=array();
			if($data['agency_id']){
				$user_arr['agency_id']=$data['agency_id'];
			}
			if($data['agency_id1']){
				$user_arr['agency_id1']=$data['agency_id1'];
			}
			if($data['agency_id2']){
				$user_arr['agency_id2']=$data['agency_id2'];
			}
			if($info_user && $user_arr){
				$info_user_edit = db('info_user')->where('tj_agent',$data['id'])->update($user_arr);
			}
			//修改当前商家
			$res = db('info_agent')->where('id',$data['id'])->update($data);
			if($res){
				return json(['code'=>200,'msg'=>'修改成功']);
			}else{
				return json(['code'=>400,'msg'=>'修改失败']);
			}
		}
		return $this->fetch();
	}

	//会员编辑
	public function edit_user()
	{
		
		$id = input('id');

		$user_level = session('user_level');

		//获取用户信息
		$user = db('info_user')->where('id',$id)->field('level,agency_id,agency_id1,agency_id2,tj_agent,id')->find();
		$this->assign('user',$user);

		$province_where['user_level']=4;
		$agency_where['user_level']=2;
		$area_where['user_level']=3;
		//获取运营中心列表
		if($user_level==1){//平台
			$agency_where['oem_id']=session('d_id');
		}

		if($user_level==4){//省级代理
			$agency_where['province_id']=session('d_id');
		}

		if($user_level==2){//省级代理
			$area_where['agency_id']=session('d_id');
		}

		$province = db('info_oem')->field('id,user_name')->where($province_where)->select();
		$agency = db('info_oem')->field('id,user_name')->where($agency_where)->select();
		$area = db('info_oem')->field('id,user_name')->where($area_where)->select();

		$this->assign('province',$province);
		$this->assign('agency',$agency);
		$this->assign('area',$area);
		
		if(request()->isPost()){
			$data = input('post.'); 
			$res = db('info_user')->where('id',$data['id'])->update($data);
			if($res){
				return json(['code'=>200,'msg'=>'修改成功']);
			}else{
				return json(['code'=>400,'msg'=>'修改失败']);
			}
		}
		return $this->fetch();
	}
	
	public function get_agency_id()
	{
		$where['province_id'] = input('agency_id');
		$where['user_level'] = 2;
		$province = db('info_oem')->field('id,user_name')->where($where)->select();
		return json(['data'=>$province]);
	}
	
	public function get_agency_id1()
	{
		$where['agency_id'] = input('agency_id1');
		$where['user_level'] = 3;
		$agency = db('info_oem')->field('id,user_name')->where($where)->select();
		return json(['data'=>$agency]);
	}


	//商家余额记录
	public function show_charge()
	{
		$param=input();  
		$where['agent_id'] = input('id');
		if(!empty($param['begin_time']) && !empty($param['end_time'])){
			$where['add_time'] = ['between time',[$param['begin_time'],$param['end_time']]];
		} 
		$list=Db::table('log_agent_charge')
			    ->where($where)
				->order('add_time desc')
			    ->paginate(20,false,['query'=>request()->param()]);
			    
        $this->assign('list',$list);
		$this->assign('id',input('id'));
		$this->assign('begin_time',input('begin_time'));
        $this->assign('end_time',input('end_time'));
		return $this->fetch();
	}

	//会员和专员余额记录
	public function log_user()
	{
		$param=input();  
		$where['u_id'] = input('id');
		if(!empty($param['begin_time']) && !empty($param['end_time'])){
			$where['add_time'] = ['between time',[$param['begin_time'],$param['end_time']]];
		} 
		$list=Db::table('log_user_charge')
			    ->where($where)
				->order('add_time desc')
			    ->paginate(20,false,['query'=>request()->param()]);
			    
        $this->assign('list',$list);
		$this->assign('id',input('id'));
		$this->assign('begin_time',input('begin_time'));
        $this->assign('end_time',input('end_time'));
		return $this->fetch();
	}
	
	
	//统计商家数据
	public function agent_count()
    {
		$agent_id=input('id');	
    	$where['agent_id']=$agent_id;	
		$where1['agent_id']=$agent_id;
		$mems=db('info_user')->where("tj_agent",$agent_id)->count();
		$today_users=db("info_user")->where("tj_agent",$agent_id)->whereTime('add_time', 'today')->cache(60)->count();
	   	$week_users=db("info_user")->where("tj_agent",$agent_id)->whereTime('add_time', 'week')->cache(60)->count();
		$month_users=db("info_user")->where("tj_agent",$agent_id)->whereTime('add_time', 'month')->cache(60)->count();
		$last_month_users=db("info_user")->where("tj_agent",$agent_id)->whereTime('add_time', 'last month')->cache(60)->count();
	    $this->assign('today_mems',$today_users?$today_users:0);
		$this->assign('week_mems',$week_users?$week_users:0);
		$this->assign('month_mems',$month_users?$month_users:0);
		$this->assign('last_month_mems',$last_month_users?$last_month_users:0);
		$this->assign('mems',$mems?$mems:0);
		
		$list=db("log_paylog_copy")->where($where)->field("uid,balance,order_type,score,sy_type,payment_type")->select();
		$logs=db('log_paylog_copy')->where($where)->cache(30)->sum("balance");	   
	   	$today_logs=db("log_paylog_copy")->where($where)->whereTime('add_time', 'today')->cache(30)->sum("balance");
	   	$week_logs=db("log_paylog_copy")->where($where)->whereTime('add_time', 'week')->cache(30)->sum("balance");
		$month_logs=db("log_paylog_copy")->where($where)->whereTime('add_time', 'month')->cache(30)->sum("balance");
		$last_month_logs=db("log_paylog_copy")->where($where)->whereTime('add_time', 'last month')->cache(30)->sum("balance");
	   	$this->assign("logs",$logs?$logs:0);
	   	$this->assign("today_logs",$today_logs?$today_logs:0);
	   	$this->assign("week_logs",$week_logs?$week_logs:0);
		$this->assign("month_logs",$month_logs?$month_logs:0);
		$this->assign("last_month_logs",$last_month_logs?$last_month_logs:0);

		$bishu_where['order_type'] = ['not in','3,4,5'];
		$bishu_where['state'] = 2;
		$bishu_where['agent_id'] = $agent_id;
		$counts=db('log_paylog')->where($bishu_where)->cache(30)->count();
	    $today_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'today')->cache(30)->count();
	   	$week_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'week')->cache(30)->count();
		$month_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'month')->cache(30)->count();
		$last_month_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'last month')->cache(30)->count();
	   	$this->assign("counts",$counts?$counts:0);
	   	$this->assign("today_counts",$today_counts?$today_counts:0);
	   	$this->assign("week_counts",$week_counts?$week_counts:0);
		$this->assign("month_counts",$month_counts?$month_counts:0);
		$this->assign("last_month_counts",$last_month_counts?$last_month_counts:0);
		
		$where['balance']=['<',0];
		$where['order_type']=['in','1,3,7'];
	    $today_scores=db("log_agent_score")->where($where)->whereTime('add_time', 'today')->cache(30)->sum("balance");
	   	$week_scores=db("log_agent_score")->where($where)->whereTime('add_time', 'week')->cache(30)->sum("balance");
		$month_scores=db("log_agent_score")->where($where)->whereTime('add_time', 'month')->cache(30)->sum("balance");
		$last_month_scores=db("log_agent_score")->where($where)->whereTime('add_time', 'last month')->cache(30)->sum("balance");
	   	$total_scores=db("log_agent_score")->where($where)->cache(30)->sum("balance");
		
		$this->assign("today_scores",$today_scores?$today_scores:0);
	   	$this->assign("week_scores",$week_scores?$week_scores:0);
		$this->assign("month_scores",$month_scores?$month_scores:0);
		$this->assign("last_month_scores",$last_month_scores?$last_month_scores:0);
		$this->assign("total_scores",$total_scores?$total_scores:0);

		$where1['balance']=['>',0];
		$where1['order_type']=['in','1,3,7'];
	    $today_scores1=db("log_agent_score")->where($where1)->whereTime('add_time', 'today')->cache(30)->sum("balance");
	   	$week_scores1=db("log_agent_score")->where($where1)->whereTime('add_time', 'week')->cache(30)->sum("balance");
		$month_scores1=db("log_agent_score")->where($where1)->whereTime('add_time', 'month')->cache(30)->sum("balance");
		$last_month_scores1=db("log_agent_score")->where($where1)->whereTime('add_time', 'last month')->cache(30)->sum("balance");
	   	$total_scores1=db("log_agent_score")->where($where1)->cache(30)->sum("balance");
	   	
		$this->assign("today_scores1",$today_scores1?$today_scores1:0);
	   	$this->assign("week_scores1",$week_scores1?$week_scores1:0);
		$this->assign("month_scores1",$month_scores1?$month_scores1:0);
		$this->assign("last_month_scores1",$last_month_scores1?$last_month_scores1:0);
		$this->assign("total_scores1",$total_scores1?$total_scores1:0);
		
		$cz_where['a.order_type'] = 8;
		$cz_where['a.state'] = 2;
		$cz_where['a.tj_agent_id'] = $agent_id;
		$today_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')	
							->where($cz_where)
							->whereTime('a.add_time', 'today')
							->select();	
								
		$week_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->whereTime('a.add_time', 'week')
							->select();		
		
		$month_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->whereTime('a.add_time', 'month')
							->select();	
		
		$last_month_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->whereTime('a.add_time', 'last month')
							->select();		
							
		$all_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->select();						
		
		$cz_info['today_total_cz'] 	= $today_total_cz[0]['balance'];
		$cz_info['week_total_cz'] 	= $week_total_cz[0]['balance'];
		$cz_info['month_total_cz'] 	= $month_total_cz[0]['balance'];
		$cz_info['last_month_total_cz'] 	= $last_month_total_cz[0]['balance'];
		$cz_info['all_total_cz'] 	= $all_total_cz[0]['balance'];
		$this->assign("cz_info",$cz_info);
    	return $this->fetch();
   }
	
	/**
	 * 代理，运营商 统计
	 * $level 1省代理  2市代理
	 * */
	public function oem_count()
    {
    	$level=input('level');
		if($level==1){//市代理
			$u_where['agency_id1'] = input('id');
			$bishu_where['agency_id1'] = input('id');
			$cz_where['a.agency_id1'] = input('id');
		}
		if($level==2){//区域运营商
			$u_where['agency_id2'] = input('id');
			$bishu_where['agency_id1'] = input('id');
			$cz_where['a.agency_id2'] = input('id');
		}
		if($level==4){//省代理
			$map['province_id']=input('id');
			$province=db("info_oem")->where($map)->field("id")->select();
			$province_arr=array();
			foreach($province as $val){
				$province_arr[]=$val['id'];
			}
			$province=implode(',',$province_arr);
			$u_where['agency_id1'] = ['in',$province];
			$bishu_where['agency_id1'] = ['in',$province];
			$cz_where['a.agency_id1'] = ['in',$province];
		}
    	$where['oem_id']=input('id');	
		$where1['oem_id']=input('id');
		$mems=db('info_user')->where($u_where)->count();
		$today_users=db("info_user")->where($u_where)->whereTime('add_time', 'today')->cache(60)->count();
	   	$week_users=db("info_user")->where($u_where)->whereTime('add_time', 'week')->cache(60)->count();
		$month_users=db("info_user")->where($u_where)->whereTime('add_time', 'month')->cache(60)->count();
		$last_month_users=db("info_user")->where($u_where)->whereTime('add_time', 'last month')->cache(60)->count();
	    $this->assign('today_mems',$today_users?$today_users:0);
		$this->assign('week_mems',$week_users?$week_users:0);
		$this->assign('month_mems',$month_users?$month_users:0);
		$this->assign('last_month_mems',$last_month_users?$last_month_users:0);
		$this->assign('mems',$mems?$mems:0);
		
		$list=db("log_paylog_copy")->where($u_where)->field("uid,balance,order_type,score,sy_type,payment_type")->select();
		$logs=db('log_paylog_copy')->where($u_where)->cache(30)->sum("balance");	   
	   	$today_logs=db("log_paylog_copy")->where($u_where)->whereTime('add_time', 'today')->cache(30)->sum("balance");
	   	$week_logs=db("log_paylog_copy")->where($u_where)->whereTime('add_time', 'week')->cache(30)->sum("balance");
		$month_logs=db("log_paylog_copy")->where($u_where)->whereTime('add_time', 'month')->cache(30)->sum("balance");
		$last_month_logs=db("log_paylog_copy")->where($u_where)->whereTime('add_time', 'last month')->cache(30)->sum("balance");
	   	$this->assign("logs",$logs?$logs:0);
	   	$this->assign("today_logs",$today_logs?$today_logs:0);
	   	$this->assign("week_logs",$week_logs?$week_logs:0);
		$this->assign("month_logs",$month_logs?$month_logs:0);
		$this->assign("last_month_logs",$last_month_logs?$last_month_logs:0);

		$bishu_where['order_type'] = ['not in','3,4,5'];
		$bishu_where['state'] = 2;
		$counts=db('log_paylog')->where($bishu_where)->cache(30)->count();
	    $today_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'today')->cache(30)->count();
	   	$week_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'week')->cache(30)->count();
		$month_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'month')->cache(30)->count();
		$last_month_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'last month')->cache(30)->count();
	   	$this->assign("counts",$counts?$counts:0);
	   	$this->assign("today_counts",$today_counts?$today_counts:0);
	   	$this->assign("week_counts",$week_counts?$week_counts:0);
		$this->assign("month_counts",$month_counts?$month_counts:0);
		$this->assign("last_month_counts",$last_month_counts?$last_month_counts:0);
		
		$where['balance']=['<',0];
		$where['order_type']=['in','7,8'];
	    $today_scores=db("log_oem_score")->where($where)->whereTime('add_time', 'today')->cache(30)->sum("balance");
	   	$week_scores=db("log_oem_score")->where($where)->whereTime('add_time', 'week')->cache(30)->sum("balance");
		$month_scores=db("log_oem_score")->where($where)->whereTime('add_time', 'month')->cache(30)->sum("balance");
		$last_month_scores=db("log_oem_score")->where($where)->whereTime('add_time', 'last month')->cache(30)->sum("balance");
	   	$total_scores=db("log_oem_score")->where($where)->cache(30)->sum("balance");
		
		$this->assign("today_scores",$today_scores?$today_scores:0);
	   	$this->assign("week_scores",$week_scores?$week_scores:0);
		$this->assign("month_scores",$month_scores?$month_scores:0);
		$this->assign("last_month_scores",$last_month_scores?$last_month_scores:0);
		$this->assign("total_scores",$total_scores?$total_scores:0);

		$where1['balance']=['>',0];
		$where1['order_type']=['in','7,8'];
	    $today_scores1=db("log_oem_score")->where($where1)->whereTime('add_time', 'today')->cache(30)->sum("balance");
	   	$week_scores1=db("log_oem_score")->where($where1)->whereTime('add_time', 'week')->cache(30)->sum("balance");
		$month_scores1=db("log_oem_score")->where($where1)->whereTime('add_time', 'month')->cache(30)->sum("balance");
		$last_month_scores1=db("log_oem_score")->where($where1)->whereTime('add_time', 'last month')->cache(30)->sum("balance");
	   	$total_scores1=db("log_oem_score")->where($where1)->cache(30)->sum("balance");
	   	
		$this->assign("today_scores1",$today_scores1?$today_scores1:0);
	   	$this->assign("week_scores1",$week_scores1?$week_scores1:0);
		$this->assign("month_scores1",$month_scores1?$month_scores1:0);
		$this->assign("last_month_scores1",$last_month_scores1?$last_month_scores1:0);
		$this->assign("total_scores1",$total_scores1?$total_scores1:0);
		
		$cz_where['a.order_type'] = 8;
		$cz_where['a.state'] = 2;
		$today_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')	
							->where($cz_where)
							->whereTime('a.add_time', 'today')
							->select();	
								
		$week_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->whereTime('a.add_time', 'week')
							->select();		
		
		$month_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->whereTime('a.add_time', 'month')
							->select();	
		
		$last_month_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->whereTime('a.add_time', 'last month')
							->select();	
							
		$all_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->select();						
		
		$cz_info['today_total_cz'] 	= $today_total_cz[0]['balance'];
		$cz_info['week_total_cz'] 	= $week_total_cz[0]['balance'];
		$cz_info['month_total_cz'] 	= $month_total_cz[0]['balance'];
		$cz_info['last_month_total_cz'] 	= $last_month_total_cz[0]['balance'];
		$cz_info['all_total_cz'] 	= $all_total_cz[0]['balance'];
		$this->assign("cz_info",$cz_info);
    	return $this->fetch();
   }

    //编辑市场专员
    public function pt_edit()
	{
		if(request()->isPost()){ 
			if(input('agency_id1')){
				$data['agency_id1'] = input('agency_id1'); 
			}
			if(input('agency_id2')){
				$data['agency_id2'] = input('agency_id2');
			}
			
			if(input('agency_id1') || input('agency_id2')){
				//变更变更层级
				$info_agent = db('info_agent')->where('sc_id',input('id'))->select();
				if($info_agent){
					$sc_agent = db('info_agent')->where('sc_id',input('id'))->update($data);
					if($sc_agent){
						$agentarr=array();
						foreach($info_agent as $vo){
							$agentarr[]=$vo['id'];
						}
						$agentstr=implode(",", $agentarr);    //去重分割数组
						$agentstr=trim($agentstr,',');                    //商家不存在，或者一个时去除两边的符号
						$agent_where['tj_agent'] =['in',$agentstr];
						$info_user = db('info_user')->where($agent_where)->update($data);
					}
			  	}
			}
			//变更分佣
			$data['sc_bili'] = input('sc_bili');  
			$row = db('info_user')->where('id',input('id'))->update($data);
			if($row){
				return json(['code'=>200,'msg'=>'修改成功']);
			}else{
				return json(['code'=>400,'msg'=>'修改失败']);
			}
		}
		$res = db('info_user')->where('id',input('id'))->find();
		$user_level=session("user_level");
		$d_id=session("d_id");
		$where['status'] = 1;
		$data=array();
		$list=array();
		//平台编辑
		if($user_level==1){
			//所有市代
			$where['user_level'] = 2;
			$data = db('info_oem')->where($where)->select();
		}
		//省代编辑
		if($user_level==4){
			//省代下的市代
			$where['province_id'] = $d_id;
			$where['user_level'] = 2;
			$data = db('info_oem')->where($where)->select();
			}
		
		//平台、省代编辑区域运营商
        if($user_level==1 || $user_level==4){
			
			$area_where['agency_id'] = $res['agency_id1'];
			$area_where['user_level'] = 3;
			$list = db('info_oem')->where($area_where)->select();
		}
		
		//市代编辑区域
		if($user_level==2){
			$where['agency_id'] = $d_id;
			$where['user_level'] = 3;
			$list = db('info_oem')->where($where)->select();
			}
		
		$this->assign('data',$data);
		$this->assign('list',$list);
		$this->assign('res',$res);
		return $this->fetch();
	}

    //统计市场专员下商家数据
	public function pt_count()
    {
    	//查询出商家ID
		$agent = db('info_agent')->where('sc_id',input('id'))->field('id')->select();
		$agent_arr=array();
		foreach($agent as $val){
			$agent_arr[]=$val['id'];
		}
		$agent_id=implode(',',$agent_arr);
    	$where['agent_id']=['in',$agent_id];	
		$where1['agent_id']=['in',$agent_id];
		$where_agent['tj_agent']=['in',$agent_id];
		
		$mems=db('info_user')->where($where_agent)->count();
		$today_users=db("info_user")->where($where_agent)->whereTime('add_time', 'today')->cache(60)->count();
	   	$week_users=db("info_user")->where($where_agent)->whereTime('add_time', 'week')->cache(60)->count();
		$month_users=db("info_user")->where($where_agent)->whereTime('add_time', 'month')->cache(60)->count();
		$last_month_users=db("info_user")->where($where_agent)->whereTime('add_time', 'last month')->cache(60)->count();
		
		$this->assign('today_mems',$today_users?$today_users:0);
		$this->assign('week_mems',$week_users?$week_users:0);
		$this->assign('month_mems',$month_users?$month_users:0);
		$this->assign('last_month_mems',$last_month_users?$last_month_users:0);
		$this->assign('mems',$mems?$mems:0);
	  
		
		$list=db("log_paylog_copy")->where($where)->field("uid,balance,order_type,score,sy_type,payment_type")->select();
		$logs=db('log_paylog_copy')->where($where)->cache(30)->sum("balance");	   
	   	$today_logs=db("log_paylog_copy")->where($where)->whereTime('add_time', 'today')->cache(30)->sum("balance");
	   	$week_logs=db("log_paylog_copy")->where($where)->whereTime('add_time', 'week')->cache(30)->sum("balance");
		$month_logs=db("log_paylog_copy")->where($where)->whereTime('add_time', 'month')->cache(30)->sum("balance");
		$last_month_logs=db("log_paylog_copy")->where($where)->whereTime('add_time', 'last month')->cache(30)->sum("balance");
	
		$this->assign("logs",$logs?$logs:0);
	   	$this->assign("today_logs",$today_logs?$today_logs:0);
	   	$this->assign("week_logs",$week_logs?$week_logs:0);
		$this->assign("month_logs",$month_logs?$month_logs:0);
		$this->assign("last_month_logs",$last_month_logs?$last_month_logs:0);
	   

		$bishu_where['order_type'] = ['not in','3,4,5'];
		$bishu_where['state'] = 2;
		$bishu_where['agent_id'] = ['in',$agent_id];
		$counts=db('log_paylog')->where($bishu_where)->cache(30)->count();
	    $today_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'today')->cache(30)->count();
	   	$week_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'week')->cache(30)->count();
		$month_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'month')->cache(30)->count();
		$last_month_counts=db("log_paylog")->where($bishu_where)->whereTime('add_time', 'last month')->cache(30)->count();

		$this->assign("counts",$counts?$counts:0);
	   	$this->assign("today_counts",$today_counts?$today_counts:0);
	   	$this->assign("week_counts",$week_counts?$week_counts:0);
		$this->assign("month_counts",$month_counts?$month_counts:0);
		$this->assign("last_month_counts",$last_month_counts?$last_month_counts:0);
	
		
		$where['balance']=['<',0];
		$where['order_type']=['in','1,3,7'];
	    $today_scores=db("log_agent_score")->where($where)->whereTime('add_time', 'today')->cache(30)->sum("balance");
	   	$week_scores=db("log_agent_score")->where($where)->whereTime('add_time', 'week')->cache(30)->sum("balance");
		$month_scores=db("log_agent_score")->where($where)->whereTime('add_time', 'month')->cache(30)->sum("balance");
		$last_month_scores=db("log_agent_score")->where($where)->whereTime('add_time', 'last month')->cache(30)->sum("balance");
		$total_scores=db("log_agent_score")->where($where)->cache(30)->sum("balance");
	
		$this->assign("today_scores",$today_scores?$today_scores:0);
	   	$this->assign("week_scores",$week_scores?$week_scores:0);
		$this->assign("month_scores",$month_scores?$month_scores:0);
		$this->assign("last_month_scores",$last_month_scores?$last_month_scores:0);
		$this->assign("total_scores",$total_scores?$total_scores:0);
		
		$where1['balance']=['>',0];
		$where1['order_type']=['in','1,3,7'];
	    $today_scores1=db("log_agent_score")->where($where1)->whereTime('add_time', 'today')->cache(30)->sum("balance");
	   	$week_scores1=db("log_agent_score")->where($where1)->whereTime('add_time', 'week')->cache(30)->sum("balance");
		$month_scores1=db("log_agent_score")->where($where1)->whereTime('add_time', 'month')->cache(30)->sum("balance");
		$last_month_scores1=db("log_agent_score")->where($where1)->whereTime('add_time', 'last month')->cache(30)->sum("balance");
		   
		$total_scores1=db("log_agent_score")->where($where1)->cache(30)->sum("balance");
	
		$this->assign("today_scores1",$today_scores1?$today_scores1:0);
	   	$this->assign("week_scores1",$week_scores1?$week_scores1:0);
		$this->assign("month_scores1",$month_scores1?$month_scores1:0);
		$this->assign("last_month_scores1",$last_month_scores1?$last_month_scores1:0);
		$this->assign("total_scores1",$total_scores1?$total_scores1:0);
	
		
		$cz_where['a.order_type'] = 8;
		$cz_where['a.state'] = 2;
		$cz_where['a.tj_agent_id'] = session("agent_id");
		$today_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')	
							->where($cz_where)
							->whereTime('a.add_time', 'today')
							->select();	
								
		$week_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->whereTime('a.add_time', 'week')
							->select();		
		
		$month_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->whereTime('a.add_time', 'month')
							->select();	
		
		$last_month_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->whereTime('a.add_time', 'last month')
							->select();		
							
		$all_total_cz = db('log_paylog')
							->alias('a')
							->field('sum(a.balance) as balance')
							->join('info_user b','a.uid = b.id','LEFT')		
							->where($cz_where)
							->select();						
		
		$cz_info['today_total_cz'] 	= $today_total_cz[0]['balance'];
		$cz_info['week_total_cz'] 	= $week_total_cz[0]['balance'];
		$cz_info['month_total_cz'] 	= $month_total_cz[0]['balance'];
		$cz_info['last_month_total_cz'] 	= $last_month_total_cz[0]['balance'];
		$cz_info['all_total_cz'] 	= $all_total_cz[0]['balance'];
		
		$this->assign("cz_info",$cz_info); 
    	return $this->fetch();
   } 
}
